I know that this question has already been answered, but here is the code for the loop through receiving the GridView data and storing it in the database:
Using libraries:
- using System.Data;
- using System.Data.SqlClient;
- using System.Web.Configuration;
- using System.Data.Odbc;
Code for:
// this is a variable that have the Query or SQL Commands. string DataBaseQuery = "UPDATE [table] SET [variable2] = @variable2, [variable3] = @variable3) WHERE [variable1] = @variable1"; //Click Event from a LinkButton. protected void LinkButton1_Click(object sender, EventArgs e) { //"ConnectionString" its the string connection for your DataBase (often get from the WebConfig File or a DataSource element. using (SqlConnection connection = new SqlConnection(ConnectionString)) { //this is for open the database using the string connection. connection.Open(); //this is the algorithm for going through the entire GridView. for (int i = 0; i < GridView1.Rows.Count; i++) { //"DataBaseQuery" it a string variable that have the Query or SQL Commands. SqlCommand cmd = new SqlCommand(DataBaseQuery, conexion); //this case it for obtain the text variable of the first column of the gridview (in my case it was the ID of the register). cmd.Parameters.AddWithValue("@variable1", ((Label)GridView1.Rows[i].Cells[0].FindControl("Label1")).Text.ToString()); //this case it for obtain the selected value of a DropDownList that were in the 14 th column) cmd.Parameters.AddWithValue("@variable2", ((DropDownList)GridView1.Rows[i].Cells[15].FindControl("DropDownlist2")).SelectedValue.ToString()); //this command it for obtain the text of a textbox that is in the 15 th column of the gridview. cmd.Parameters.AddWithValue("@variable3", ((TextBox)GridView1.Rows[i].Cells[16].FindControl("TextBox17")).Text.ToString()); cmd.ExecuteNonQuery(); } //after going through all the gridview you have to close the connection to the DataBase. connection.Close(); } }
Of course, you need to configure the code for a specific case, but it is very simple. In this code, you have an example to get values โโfor other objects like labes, textbox and dropdownlist in gridview.
I suffered a lot to run this code (I'm not very good at programming), but I am happy to help.
NOTE. To count gridview columns you must start from scratch. NOTE2: Sorry for my poor English, by the way ... This is not my language of nature.
source share