Save And Retrieve Dynamic TextBox Values In GridView to SQL Server

In this article you will learn how to save and retrieve dynamic TextBox Values in GridView to SQL Server.

The title says it all. So without wasting any time let’s quickly go through the theme of this article—How we are going to implement the desired functioning in SQL Server? 

Getting Started

Step 1:

First of all let’s create a simple sample Table in SQL Server. In my case am going to name it ‘DemoTab’ having attribute ID.

(Just like that..)

DemoTab

Step 2:

Now let’s proceed to ASPX source and add a Button for saving the data to the database.
(Just like that..)

add a Button

Step 3:

Now, am going to create a method for saving the data to the database. But before that we need to establish the database connection. (Am not showing how to do that, but if you’re beginner in that case you can go through my article.

Just go to the web.config and paste below connection string there. Change some credentials such as per your SQL server.

  1. <connectionStrings>  
  2.     <add name="DBCon" connectionString="Data Source= ABHI-PC; Initial Catalog=DemoDB; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />   
  3. </connectionStrings>  
Step 4:

As you can see we are done with establishing connection string. Now we can proceed to the next step which is creation of the method for saving the data to the database. For that just add the following namespaces as shown below:
  1. using System.Text;  
  2. using System.Data.SqlClient;  
  3. using System.Collections.Specialized;  
(These namespaces are for SqlClient, String Collections and StringBuilder built-in methods. We are going to use their functionality later.)

Step 5:

Now let’s create the method for calling the connection strings.
  1. private string GetConnectionString()   
  2. {  
  3.     // "DBCon" is the name of the Connection String  
  4.     return System.Configuration.ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString;  
  5. }  
Step 6:

Now, am going to show the code for INSERT method. Take a look,
  1. // An Insert Method  
  2. private void InsertRecords(StringCollection sc)  
  3. {  
  4.     SqlConnection conn = new SqlConnection(GetConnectionString());  
  5.     StringBuilder sb = new StringBuilder(string.Empty);  
  6.     string[] splitItems = null;  
  7.     foreach(string item in sc)  
  8.     {  
  9.         const string sqlStatement = "INSERT INTO DemoTab (Column1,Column2,Column3,Column4,Column5) VALUES";  
  10.         if (item.Contains(","))  
  11.         {  
  12.             splitItems = item.Split(",".ToCharArray());  
  13.             sb.AppendFormat("{0}('{1}','{2}','{3}',’{4}’,’{5}’); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2]);  
  14.         }  
  15.     }  
  16.     try {  
  17.         conn.Open();  
  18.         SqlCommand cmd = new SqlCommand(sb.ToString(), conn);  
  19.         cmd.CommandType = CommandType.Text;  
  20.         cmd.ExecuteNonQuery();  
  21.         Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script""alert('Records are Saved Successfuly!');"true);  
  22.     } catch (System.Data.SqlClient.SqlException ex) {  
  23.         string msg = "Insert Error:";  
  24.         msg += ex.Message;  
  25.         throw new Exception(msg);  
  26.     } finally {  
  27.         conn.Close();  
  28.     }  
  29. }  
Step 7:

This is the final step.

Now, am going to create a Button Click event. So that we can call the method “InsertRecords” after extracting the dynamic TextBox values.

Here’s a code..
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     int rowIndex = 0;  
  4.     StringCollection sc = new StringCollection();  
  5.     if (ViewState["CurrentTable"] != null)  
  6.     {  
  7.         DataTable dtCurrentTable = (DataTable) ViewState["CurrentTable"];  
  8.         if (dtCurrentTable.Rows.Count > 0) {  
  9.             for (int i = 1; i <= dtCurrentTable.Rows.Count; i++) {  
  10.                 TextBox box1 = (TextBox) Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");  
  11.                 TextBox box2 = (TextBox) Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");  
  12.                 TextBox box3 = (TextBox) Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");  
  13.                 TextBox box4 = (TextBox) Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox4");  
  14.                 TextBox box5 = (TextBox) Gridview1.Rows[rowIndex].Cells[5].FindControl("TextBox5");  
  15.                 // Getting Values from TextBoxes  
  16.                 sc.Add(box1.Text + "," + box2.Text + "," + box3.Text + “, ”+box4.Text + "," + box5.Text);  
  17.                 rowIndex++;  
  18.             }  
  19.             // Call the method   
  20.             InsertRecords(sc);  
  21.         }  
  22.     }  
  23. }  
That’s all guys.

Just Run the code and it will directly take you here,

save

Now enter the values and enjoy.

I hope this article helps. Cheers!!
 
Read more articles on SQL Server: