Hi AbdulHaque,
Refer the below code for insert on click of button outside the gridview.
C#
protected void btnInsert(object sender, EventArgs e)
{
foreach (GridViewRow row in Gridview1.Rows)
{
string rowNo = row.Cells[0].Text;
string header1 = (row.FindControl("TextBox1") as TextBox).Text;
string header2 = (row.FindControl("TextBox2") as TextBox).Text;
string header3 = (row.FindControl("TextBox3") as TextBox).Text;
// Insert code here
Insert(rowNo, header1, header2, header3);
}
}
private void Insert(string rowNo, string header1, string header2, string header3)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Test VALUES(@RowNo,@Header1,@Header2,@Header3)"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@RowNo", rowNo);
cmd.Parameters.AddWithValue("@Header1", header1);
cmd.Parameters.AddWithValue("@Header2", header2);
cmd.Parameters.AddWithValue("@Header3", header3);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
VB.Net
Protected Sub btnInsert(sender As Object, e As EventArgs)
For Each row As GridViewRow In Gridview1.Rows
Dim rowNo As String = row.Cells(0).Text
Dim header1 As String = TryCast(row.FindControl("TextBox1"), TextBox).Text
Dim header2 As String = TryCast(row.FindControl("TextBox2"), TextBox).Text
Dim header3 As String = TryCast(row.FindControl("TextBox3"), TextBox).Text
' Insert code here
Insert(rowNo, header1, header2, header3)
Next
End Sub
Private Sub Insert(rowNo As String, header1 As String, header2 As String, header3 As String)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("INSERT INTO Test VALUES(@RowNo,@Header1,@Header2,@Header3)")
cmd.Connection = con
cmd.Parameters.AddWithValue("@RowNo", rowNo)
cmd.Parameters.AddWithValue("@Header1", header1)
cmd.Parameters.AddWithValue("@Header2", header2)
cmd.Parameters.AddWithValue("@Header3", header3)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub