Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

c# - inserting items of listbox into sql server database

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...