Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
901 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...