You can easily access the fields using row.Cells[0].Text where 0 is the index of first column
HTML
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<hr />
<asp:Button Text="Insert" runat="server" OnClick = "Insert" />
Namespaces
using System.Data;
using System.Data.SqlClient;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void Insert(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
string id = row.Cells[0].Text;
string name = row.Cells[2].Text;
string country = row.Cells[2].Text;
string conString = @"Data Source=.\SQL2008R2;Initial Catalog=AjaxSamples;User id = sa;password=pass@123";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@CustomerId, @Name, @Country)", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@CustomerId", row.Cells[0].Text);
cmd.Parameters.AddWithValue("@Name", row.Cells[1].Text);
cmd.Parameters.AddWithValue("@Country", row.Cells[2].Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Table
