Hi Priyanka12,
Try the following sample.
Html Code..
<div>
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField DataField="Name" HeaderText="Customer Name" />
<asp:BoundField DataField="City" HeaderText="Customer City" />
<asp:BoundField DataField="BirthDate" HeaderText="Date of Birth" DataFormatString="{0:yyyy-MM-dd}" />
</Columns>
</asp:GridView>
<br />
<asp:Button Text="Submit" runat="server" ID="btnSubmit" OnClick="Save" />
</div>
C# Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.gvUsers.DataSource = this.BindGrid();
this.gvUsers.DataBind();
}
}
protected void Save(object sender, EventArgs e)
{
foreach (GridViewRow row in this.gvUsers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
this.SaveDetails(row);
}
}
}
private DataTable BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4]
{
new DataColumn("CustomerId",typeof(int))
,new DataColumn("Name",typeof(string))
,new DataColumn("City",typeof(string))
,new DataColumn("BirthDate",typeof(DateTime))});
dt.Rows.Add(1, "Ashutosh Singh", "Mumbai", "1989-01-01");
dt.Rows.Add(2, "Ramkrishna", "CA", "1987-01-01");
dt.Rows.Add(3, "John Smith", "Surat", "1988-01-01");
dt.Rows.Add(4, "Aryan Singh", "Varanasi", "1986-01-01");
return dt;
}
private void SaveDetails(GridViewRow row)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Table_Customer VALUES(@CustomerId,@CustomerName,@CustomerCity,@CustomerBirthDate)",con);
cmd.Parameters.AddWithValue("@CustomerId", row.Cells[0].Text);
cmd.Parameters.AddWithValue("@CustomerName", row.Cells[1].Text);
cmd.Parameters.AddWithValue("@CustomerCity", row.Cells[2].Text);
cmd.Parameters.AddWithValue("@CustomerBirthDate", Convert.ToDateTime(row.Cells[3].Text, System.Globalization.CultureInfo.CurrentCulture));
con.Open();
cmd.ExecuteScalar();
con.Close();
Namespaces
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
If any confusion.Please revert on the same