Save (Insert) Array of String to database in C# and VB.Net

Last Reply on Nov 21, 2014 03:27 AM By Mudassar

Posted on Nov 21, 2014 02:28 AM

I  have one problem.i do'nt know how to save data in to database from

 String nm=["Pankaj","Pravin","Parag"] 

format.

How to separe this string into separate name as like Pankaj,Pravin,Parag will be the separate.

Display using asp.net.

Posted on Nov 21, 2014 03:27 AM Modified on on Nov 21, 2014 03:44 AM

You need to create an array of string and then code as following.

C#

Namespaces

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

Code

protected void Button1_Click(object sender, EventArgs e)
{
    string[] nm = new string[3] { "Pankaj", "Pravin", "Parag" };
    foreach (string name in nm)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Names(Name) VALUES(@Name)"))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Name", name);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
}

VB.Net

Namespaces

Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient

Code

Protected Sub Button1_Click(sender As Object, e As EventArgs)
	Dim nm As String() = New String(2) {"Pankaj", "Pravin", "Parag"}
	For Each name As String In nm
		Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
		Using con As New SqlConnection(constr)
			Using cmd As New SqlCommand("INSERT INTO Names(Name) VALUES(@Name)")
				cmd.Connection = con
				cmd.Parameters.AddWithValue("@Name", name)
				con.Open()
				cmd.ExecuteNonQuery()
				con.Close()
			End Using
		End Using
	Next
End Sub