Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Sep 28, 2022, 3:44 AM EDT
Hello Naresh check below code.
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; namespace Insert_data_from_Gridview_database { public partial class _Default : System.Web.UI.Page { string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlCommand com; protected void btn_show_Click(object sender, EventArgs e) { DataSet reportData = new DataSet(); reportData.ReadXml(Server.MapPath("student.xml")); GridView1.DataSource = reportData; GridView1.DataBind(); } protected void btn_insert_Click(object sender, EventArgs e) { foreach (GridViewRow g1 in GridView1.Rows) { SqlConnection con = new SqlConnection(connStr); com = new SqlCommand("insert into student(sid,sname,smarks,saddress) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con); con.Open(); com.ExecuteNonQuery(); con.Close(); } Label1.Text = "Data saved successfully"; } } }Vishal YelveRank #178 · 13.6K reputationPosted Sep 28, 2022, 4:44 AM EDT
Hi Naresh,
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { this.BindGrid(); } } private void BindGrid() { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; string query = "SELECT * FROM Customers"; using (SqlConnection con = new SqlConnection(constr)) { using (SqlDataAdapter sda = new SqlDataAdapter(query, con)) { using (DataTable dt = new DataTable()) { sda.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } } } } protected void Insert(object sender, EventArgs e) { string name = txtName.Text; string country = txtCountry.Text; txtName.Text = ""; txtCountry.Text = ""; string query = "INSERT INTO Customers VALUES(@Name, @Country)"; string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(query)) { cmd.Parameters.AddWithValue("@Name", name); cmd.Parameters.AddWithValue("@Country", country); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } this.BindGrid(); }