Saving CheckBox Values

I am using asp.net and I am trying to store checkbox values ​​in a database. Multiple check boxes can be entered in the same field in the database. So, for example, I have two checkboxes named "Comma" and "Hyphen", and if the user checks both of them, then the database will store the values ​​",", "-". How do you do it?

thank

0


source to share


2 answers


To store multiple values ​​in one column, I would recommend using a flag enum. Here's an example using checkboxes .

If you really need to store the values ​​in comma delimited format, you can try something like this:



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

      

+1


source


I agree with David Thomas Garcia's recommendation if you can store the value in the database using an enum (as an int or something suitable for the number of options you have).

If that is not an option and you are required to store them in the database as a character string, I would 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 splitting the values ​​to be stored in the value stored in the database, but if you need you to be able to use the List and do what David Thomas Garcia mentioned in .ToArray (). Join (","); in SaveData () and in LoadData () just make a dbVal List and the syntax doesn't need to change.

0


source







All Articles