Inserting multiple values to database using single textbox with values separated with comma [,]



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.
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Name:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        Number:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</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:
create proc multiple @name varchar(50),@cellnumber int
AS
Begin
insert into people1 (name,cellnumber) values(@Name,@cellnumber);
End


Code Behind:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace _19_oct_textbox_split
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Data Source=192.168.3.48;Initial Catalog=vikram;User ID=sa;Password=Atharvana01");
            SqlCommand cmd = new SqlCommand("multiple", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();

            if (TextBox1.Text.Contains(','))//checking for you are entered single value or multiple values
            {
                string[] arryval = TextBox1.Text.Split(',');//split values with ‘,’
                int j = arryval.Length;
                int i = 0;
                for (i = 0; i < j; i++)
                {
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@Name", arryval[i]);
                    cmd.Parameters.AddWithValue("@cellnumber", TextBox2.Text);
                    cmd.ExecuteNonQuery();
                }

            }
            else
            {
                SqlCommand cm = new SqlCommand(String.Format("insert into people1 (name,cellnumber) values('{0}','{1}')", TextBox1.Text,TextBox2.Text), con);
                cm.ExecuteNonQuery();
            }
        }
    }
}
I think it is simple to understand.

Happy coding.

1 comment: