Hello,
Put Panel control (name it panThings) on your form and then move your checkboxes to that panel to group them.
Then use this code:
var things = string.Join(",", panThings.Controls.OfType<CheckBox>().Where(x => x.Checked).Select(x => x.Text.ToUpper()));
string query = "INSERT INTO TEST (things) VALUES (@things)";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.Add("@things", things);
And don't forget to add
System.Linq to your
using clause at top of the file.
[Update 1]
Suppose that you have checkboxes with texts:
Mouse, Keyboard, Hard drive, Monitor and so on.
Then if you check i.e. Mouse and Monitor checkboxes output will be:
Mouse,Monitor
And that value will be stored in DB.
[Update 2 - Answer to comment]
To restore selected items do this:
var thingsFieldValue = dt.Rows[0]["PUT_YOUR_THINGS_DB_FIELD_NAME_HERE"].ToString();
var things = thingsFieldValue.Split(",".ToCharArray());
foreach (var thing in things)
{
var checkBox = panThings.Controls.OfType<CheckBox>().Where(x => x.Text.ToUpper() == thing).FirstOrDefault();
if (checkBox != null)
{
checkBox.Checked = true;
}
}
Cheers!