"in fact i have list box contain several items and want them to several column in the table"
That is where it gets harder.
If you are assigning one item from your ListBox to each Row, then that is easy - just loop through and execute the appropriate INSERT statement.
But a variable number of items being entered into columns is harder, as each column must both exist, and be named in the database before you can insert the values.
What do you do if you have 5 columns in your table, and 6 entries in the ListBox? Or 5 columns, and 4 entries? Which one gets missed out?
It's not complicated from a code point of view to do something that works for a specific combination of List box/columns, but to do it for a more general case is considerably harder.
What are you trying to achieve here? Why have you designed your database this way?
"for example :cod=1 ,name=pizza ,count=2 and price=8$
cod=2,name=soda ,count=2 and price
i want 1click transfer in the 4column in table"
OK, So you have a number of rows in your list box, which contain items separated by commas.
I would start by getting the list box contents, one by one:
foreach (object o in myListBox.Items)
{
string s = o as string;
if (s != null)
{
...
}
}
The next problem is to break the string into the various fields. How you do this depends on how much you trust the code that put them in there in the first place... :laugh:
The easiest way is to split the string into the various parts, one for each section separated by comma. That should give you and array containing "xxx=yyy", so you need to process that to work out where each part should go. Or, if you truyst the list box only to contain valid information, you could just split them again:
string[] parts = s.Split(',');
string code = parts[0].Split('=')[1].Trim();
string name = parts[1].Split('=')[1].Trim();
string count = parts[2].Split('=')[1].Trim();
string price = parts[3].Split('=')[1].Trim();
Personally, I don't trust any code - not even if I wrote it (it may get changed later, so I wouldn't do it like this! The way I would do it is not to put a string in in the first place - I would use a class with a ToString override instead)
You may have to do some conversions to integer, decimal, or whatever, depending on the field types in your database.
Then you can insert it to the database.
At the start of your method you will need an SqlConnection:
SqlConnection con = new SqlConnection(sonnectionString);
con.Open();
The connection string you should already have.
Then in the loop:
using (SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (code, name, count, price) VALUES (@COD, @NAM, @CNT, @PRI)", con))
{
cmd.Parameters.AddWithValue("@COD", code);
cmd.Parameters.AddWithValue("@NAM", name);
cmd.Parameters.AddWithValue("@CNT", count);
cmd.Parameters.AddWithValue("@PRI", price);
cmd.ExecuteNonQuery();
}
Done!