views:

542

answers:

2

Hello everyone,

I am using asp.net and I am trying to save checkbox values into a database. Multiple checkboxes may be entered into the same field in the database. So for instance I have two checkboxes with names "Comma" and "Hyphen" and if the user checks both of these then the database will store the values ',','-'. How do you do this?

thanks

+1  A: 

To save multiple values into the same column I'd recommend using a flag enumeration. Here is a code sample using checkboxes.

If you really have to store the values in a comma-delimited format, might try something like this:

List<string> values = new List<string>();
if (cbComma.Checked) {
   values.Add("','");
}
...
string result = values.ToArray().Join(",");
DavGarcia
A: 

I'd agree with David Thomas Garcia's recommendation if you can save the value to the database using the enumeration (as an int or whatever was appropriate for the amount of options you'll have).

If that's not an option though, and you are bound to storing them in the database as a string of characters I'd do something like the following:


private void LoadData()
{
   string dbVal = DataAccess.GetDbVal(); //Get your value from the database.
   chkComma.Checked = dbVal.Contains(",");
   chkDash.Checked = dbVal.Contains("-");
}

private void SaveData()
{
   string dbVal = "";
   if(chkComma.Checked)
      dbVal += ",";
   if(chkDash.Checked)
      dbVal += "-";
   DataAccess.SaveDbVal(dbVal); //Send the value of dbVal to your data layer to be saved.
}

Note that this does not include any separation of the values to be saved in the value stored in the database, but if you needed that you could use a List and do what David Thomas Garcia mentioned with the .ToArray().Join(","); in the SaveData() and in the LoadData() just make dbVal a List and the syntax doesn't need change.

Zemm