i was trying to save all the values/text(not the selected one but all of the values on it) in the listbox to datagridview
like this: here
here's my code in saving to datagridview
Data.con.Open();
string SaveStr = "Insert into tblOrder (CustomerID, CustomerName, CustomerAdd, Date, Orders, TotalPrice) Values (@CustomerID, @CustomerName, @CustomerAdd, @Date, @Orders, @TotalPrice)";
SqlCommand SaveCmd = new SqlCommand(SaveStr, Data.con);
SaveCmd.Parameters.AddWithValue("@CustomerID", textBox4.Text);
SaveCmd.Parameters.AddWithValue("@CustomerName", textBox5.Text);
SaveCmd.Parameters.AddWithValue("@CustomerAdd", textBox6.Text);
SaveCmd.Parameters.AddWithValue("@Date", dateTimePicker1.Value);
SaveCmd.Parameters.AddWithValue("@Orders", listBox1.Items.ToString());
SaveCmd.Parameters.AddWithValue("TotalPrice", textBox3.Text);
SaveCmd.ExecuteNonQuery();
Data.con.Close();
LoadData();
and the output is like this
THanks in advance
ListBox.Items enables you to obtain a reference to the list of items that are currently stored in the ListBox. With this reference you can obtain a count of the items in the collection. Any task can be performed with the item collection. But since you want the string to be stored to the DataBase. This might do the trick for you.
String.Join("," , listBox1.Items.OfType<string>().ToArray());
what you can do is to create a comma separated string and pass that in parameter this way you can save it . below is the updated complete code .
Data.con.Open();
string SaveStr = "Insert into tblOrder (CustomerID, CustomerName, CustomerAdd, Date, Orders, TotalPrice) Values (@CustomerID, @CustomerName, @CustomerAdd, @Date, @Orders, @TotalPrice)";
SqlCommand SaveCmd = new SqlCommand(SaveStr, Data.con);
SaveCmd.Parameters.AddWithValue("@CustomerID", textBox4.Text);
SaveCmd.Parameters.AddWithValue("@CustomerName", textBox5.Text);
SaveCmd.Parameters.AddWithValue("@CustomerAdd", textBox6.Text);
SaveCmd.Parameters.AddWithValue("@Date", dateTimePicker1.Value);
SaveCmd.Parameters.AddWithValue("@Orders", String.Join("," , listBox1.Items.OfType<string>().ToArray());
));
SaveCmd.Parameters.AddWithValue("TotalPrice", textBox3.Text);
SaveCmd.ExecuteNonQuery();
Data.con.Close();
LoadData();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.