Inserting Multiple Values to Database using Single TextBox with Values Separated with Comma

Front end Code:

Am just created 2 textboxes. In text box 1 we can enter number of values , make sure values should be separated with comma(,). Textbox2 is normal.

  1. <!DOCTYPE html>  
  2.   
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <div>  
  10.         Name:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  11.         Number:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
  12.         <asp:Button ID="Button1" runat="server" Text="Button" />  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </html>  
In the code behind am splitting textbox values and inserting into an array. By using for loop sending values to database.

Create stored procedure in database:
  1. create proc multiple @name varchar(50),@cellnumber int  
  2. AS  
  3. Begin  
  4. insert into people1 (name,cellnumber) values(@Name,@cellnumber);  
  5. End  
Code Behind
  1. using System.Web;  
  2. using System.Web.UI;  
  3. using System.Web.UI.WebControls;  
  4. using System.Data.SqlClient;  
  5. using System.Data;  
  6.   
  7. namespace _19_oct_textbox_split  
  8. {  
  9.     public partial class WebForm2 : System.Web.UI.Page  
  10.     {  
  11.         protected void Page_Load(object sender, EventArgs e)  
  12.         {  
  13.             SqlConnection con = new SqlConnection("Data Source=192.168.3.48;Initial Catalog=vikram;User ID=sa;Password=Atharvana01");  
  14.             SqlCommand cmd = new SqlCommand("multiple", con);  
  15.             cmd.CommandType = CommandType.StoredProcedure;  
  16.             con.Open();  
  17.   
  18.             if (TextBox1.Text.Contains(','))//checking for you are entered single value or multiple values  
  19.             {  
  20.                 string[] arryval = TextBox1.Text.Split(',');//split values with ‘,’  
  21.                 int j = arryval.Length;  
  22.                 int i = 0;  
  23.                 for (i = 0; i < j; i++)  
  24.                 {  
  25.                     cmd.Parameters.Clear();  
  26.                     cmd.Parameters.AddWithValue("@Name", arryval[i]);  
  27.                     cmd.Parameters.AddWithValue("@cellnumber", TextBox2.Text);  
  28.                     cmd.ExecuteNonQuery();  
  29.                 }  
  30.   
  31.             }  
  32.             else  
  33.             {  
  34.                 SqlCommand cm = new SqlCommand(String.Format("insert into people1 (name,cellnumber) values('{0}','{1}')", TextBox1.Text,TextBox2.Text), con);  
  35.                 cm.ExecuteNonQuery();  
  36.             }  
  37.         }  
  38.     }  
  39. }  
I think it is simple to understand. 
Ebook Download
View all
Learn
View all