inserting items of listbox into sql server databas

2019-09-22 05:27发布

问题:

i am inserting data in listbox1 by using this code :

if (!IsPostBack)
        {
            DataTable dt = new DataTable();
            string query = "SELECT * FROM [Qualification]";
            SqlDataAdapter objda = new SqlDataAdapter(query, conn);
            //conn.Open();
            objda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                ListBox1.DataSource = dt;
                ListBox1.DataTextField = "QDesc";
                ListBox1.DataValueField = "QID";
                ListBox1.DataBind();
            }
        }

and these items are going into listbox2 on button click

button click code is:

protected void Button1_Click1(object sender, EventArgs e)
    {
         string strItemText = "";
        string strItemValue = "";
        foreach (ListItem listItem in ListBox1.Items)
        {
            if (listItem.Selected == true)
            {
                strItemValue += listItem.Text; 
                 }
        }

        ListBox2.Items.Add(strItemText+""+ strItemValue);
        ListBox1.Items.Remove(ListBox1.SelectedItem);

    }

everything is proper till here..

i want the items in listbox2 should be populated in database table....can anyone help to suggest code for same

回答1:

Sure, you could do something like this:

using (SqlConnection c = new SqlConnection("your connection string"))
{
    c.Open();
    using (SqlCommand cmd = new SqlCommand("INSERT INTO table (field1, field2) VALUES (@field1, @field2)")
    {
        foreach (ListItem item in listbox2.Items)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@field1", item.Value);
            cmd.Parameters.AddWithValue("@field2", item.Text);

            cmd.ExecuteNonQuery();
        }
    }
}

Now clearly the INSERT statement I provided would be different, and the parameters you add would be different, and maybe you don't need the Value and the Text, but you get the idea.