locked
Getting all checked values of a checkboxLIST RRS feed

  • Question

  • User14881260 posted

    I have an ASP checkboxlist which contains 12 items. I tried using this C# code:


            string command = ("insert into GeneralInfo values (@attainment)");

            SqlCommand cmd = new SqlCommand(command, con);

            cmd.Parameters.Add("@attainment", SqlDbType.NVarChar).Value = attainment.SelectedValue;


    The problem is that it doesn't get all the checked values. Only one is being recorded. I want it to get all the checked values but also I don't know what is the good approach for this. I read some tried storing all the values it in one column by concatenating.

    Thursday, June 10, 2010 7:20 AM

Answers

  • User604186779 posted

    The problem is that it doesn't get all the checked values. Only one is being recorded. I want it to get all the checked values but also I don't know what is the good approach for this. I read some tried storing all the values it in one column by concatenating.

    you have to concatenate the checkboxlist selectedvalue like this

    string checkValue = "4,54,26,5";

    string getValue=string.empty;

    so use foreach loop get the checked id

    foreach(listitem item in Checkboxlist1.Item)
    
    {
    
    if(item.Checked == true)
    
    {
    
    getValue= item.SelectedValue + ",";
    
    }
    
    }
    
    getValue = getValue.TrimEnd(); // this will remove the last comma on the string


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 10, 2010 7:39 AM
  • User-1071856410 posted

    The problem is that it doesn't get all the checked values. Only one is being recorded. I want it to get all the checked values
     

    You need to loop through items in checkboxlist

    Get Selected Values From a CheckBoxList in C#

    but also I don't know what is the good approach for this. I read some tried storing all the values it in one column by concatenating.
     

    Depends on how you want to use the data.

    If you want to pass it as a concatenated string to your SP,  That is fine. Otherwise if you want to send each value individually that's fine too..

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 10, 2010 7:40 AM
  • User-60125975 posted

    try below code.

    string getValue="";
    for (int i = 0; i < CheckBoxList1.Items.Count; i++)
    {
          if (CheckBoxList1.Items[i].Selected)
                 getValue += CheckBoxList1.Items[i].Value + ";";
    }
    Response.Write(getValue);

    here i use ";" for separation.


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 10, 2010 10:21 PM
  • User-60125975 posted

    just change like below :

     string getValue="";  
     for (int i = 0; i < attainment.Items.Count; i++)  
     {  
         if (attainment.Items[i].Selected && i==0)  
             getValue += attainment.Items[i].Value ;
         else
             getValue +=";"+ attainment.Items[i].Value ;
    } 
    cmd.Parameters.Add("@Attainment",SqlDbType.NVarchar).Value=getValue;  
    


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 11, 2010 12:17 AM

All replies

  • User-653327211 posted

    Try the following code:

    foreach (ListItem item in attainment.Items) {

     if (item.Selected) {

    //Enter insert sql statement right here using item.value or item.text

     

     } }

    Thursday, June 10, 2010 7:27 AM
  • User-1360095595 posted

    To get all the checkboxes that are checked, you'll need to iterate through the Items collection checking the Selected property.  You can either store it as a single (comma delimited potentially) field, or you'll need to execute an insert command for each one; it depends on how you've structured your DB table(s).

    Thursday, June 10, 2010 7:29 AM
  • User604186779 posted

    The problem is that it doesn't get all the checked values. Only one is being recorded. I want it to get all the checked values but also I don't know what is the good approach for this. I read some tried storing all the values it in one column by concatenating.

    you have to concatenate the checkboxlist selectedvalue like this

    string checkValue = "4,54,26,5";

    string getValue=string.empty;

    so use foreach loop get the checked id

    foreach(listitem item in Checkboxlist1.Item)
    
    {
    
    if(item.Checked == true)
    
    {
    
    getValue= item.SelectedValue + ",";
    
    }
    
    }
    
    getValue = getValue.TrimEnd(); // this will remove the last comma on the string


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 10, 2010 7:39 AM
  • User-1071856410 posted

    The problem is that it doesn't get all the checked values. Only one is being recorded. I want it to get all the checked values
     

    You need to loop through items in checkboxlist

    Get Selected Values From a CheckBoxList in C#

    but also I don't know what is the good approach for this. I read some tried storing all the values it in one column by concatenating.
     

    Depends on how you want to use the data.

    If you want to pass it as a concatenated string to your SP,  That is fine. Otherwise if you want to send each value individually that's fine too..

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 10, 2010 7:40 AM
  • User14881260 posted

    I'll try this one and will report back tommorow.

    Thursday, June 10, 2010 8:17 AM
  • User1224194097 posted

    you can get the selected items as comma separated values and parse that string in your procedure to update your records

      string.Join(",",CheckBoxList1.Items.OfType<ListItem>().ToList().
               Where(t=>t.Selected==true).
               Select(a=>a.Text).
                ToArray<string>())


     

    Thursday, June 10, 2010 9:58 AM
  • User14881260 posted

    Where would I put this? In my button's code behind or my checkbox?

    Thursday, June 10, 2010 9:49 PM
  • User-60125975 posted

    try below code.

    string getValue="";
    for (int i = 0; i < CheckBoxList1.Items.Count; i++)
    {
          if (CheckBoxList1.Items[i].Selected)
                 getValue += CheckBoxList1.Items[i].Value + ";";
    }
    Response.Write(getValue);

    here i use ";" for separation.


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 10, 2010 10:21 PM
  • User1224194097 posted

    you are writing your code like this

            string command = ("insert into GeneralInfo values (@attainment)");

            SqlCommand cmd = new SqlCommand(command, con);

            cmd.Parameters.Add("@attainment", SqlDbType.NVarChar).Value = attainment.SelectedValue;

     

    Instead of attainment.SelectedValue copy the code that I posted.

    That will give all selected Values separated by comma like 1,2,3,4 and so on

    if your database column is a varchar, u can directly insert it without any issues

     

    post your comments if this is not clear.

    Thursday, June 10, 2010 10:22 PM
  • User14881260 posted
    1. string.Join(",",CheckBoxList1.Items.OfType<ListItem>().ToList().  
    2.          Where(t=>t.Selected==true).  
    3.          Select(a=>a.Text).  
    4.           ToArray<string>())  

    Your code is this. Honestly, I don't quite understand this code compared to venkatu's code which is easy for a newbie like me to comprehend.

    Here is my button's code behind right now:


        protected void submitButton_Click(object sender, EventArgs e)
        {
            string command = ("insert into GeneralInfo values (@FamilyName, @FirstName, @MiddleName, @Gender, @CivilStatus, @Citizenship, @BirthPlace, @CityAddress, @CityContact, @ProvinceAddress, @ProvinceContact, @Attainment)");
            SqlCommand cmd = new SqlCommand(command, con);
            cmd.Parameters.Add("@FamilyName", SqlDbType.NVarChar).Value = familyname.Text;
            cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = firstname.Text;
            cmd.Parameters.Add("@MiddleName", SqlDbType.NVarChar).Value = middlename.Text;
            cmd.Parameters.Add("@Gender", SqlDbType.NVarChar).Value = gender.SelectedValue;
            cmd.Parameters.Add("@CivilStatus", SqlDbType.NVarChar).Value = civilstatus.SelectedValue;
            cmd.Parameters.Add("@Citizenship", SqlDbType.NVarChar).Value = citizenship.Text;
            cmd.Parameters.Add("@BirthPlace", SqlDbType.NVarChar).Value = birthplace.Text;
            cmd.Parameters.Add("@CityAddress", SqlDbType.NVarChar).Value = cityaddress.Text;
            cmd.Parameters.Add("@CityContact", SqlDbType.BigInt).Value = citycontact.Text;
            cmd.Parameters.Add("@ProvinceAddress", SqlDbType.NVarChar).Value = provinceaddress.Text;
            cmd.Parameters.Add("@ProvinceContact", SqlDbType.BigInt).Value = provincecontact.Text;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

        protected void submitButton_Click(object sender, EventArgs e)
    
        {
    
            string command = ("insert into GeneralInfo values (@FamilyName, @FirstName, @MiddleName, @Gender, @CivilStatus, @Citizenship, @BirthPlace, @CityAddress, @CityContact, @ProvinceAddress, @ProvinceContact, @Attainment)");
    
            SqlCommand cmd = new SqlCommand(command, con);
    
            cmd.Parameters.Add("@FamilyName", SqlDbType.NVarChar).Value = familyname.Text;
    
            cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = firstname.Text;
    
            cmd.Parameters.Add("@MiddleName", SqlDbType.NVarChar).Value = middlename.Text;
    
            cmd.Parameters.Add("@Gender", SqlDbType.NVarChar).Value = gender.SelectedValue;
    
            cmd.Parameters.Add("@CivilStatus", SqlDbType.NVarChar).Value = civilstatus.SelectedValue;
    
            cmd.Parameters.Add("@Citizenship", SqlDbType.NVarChar).Value = citizenship.Text;
    
            cmd.Parameters.Add("@BirthPlace", SqlDbType.NVarChar).Value = birthplace.Text;
    
            cmd.Parameters.Add("@CityAddress", SqlDbType.NVarChar).Value = cityaddress.Text;
    
            cmd.Parameters.Add("@CityContact", SqlDbType.BigInt).Value = citycontact.Text;
    
            cmd.Parameters.Add("@ProvinceAddress", SqlDbType.NVarChar).Value = provinceaddress.Text;
    
            cmd.Parameters.Add("@ProvinceContact", SqlDbType.BigInt).Value = provincecontact.Text;
    
            cmd.Parameters.Add("@Attainment",SqlDbType.NVarchar).Value=attainment.SelectedValue;
    
            con.Open();
    
            cmd.ExecuteNonQuery();
    
            con.Close();
    
        }


    What do you mean by copying your code instead of attainment.selected value? How?

    Thursday, June 10, 2010 10:55 PM
  • User-60125975 posted

    try the below code :

        protected void submitButton_Click(object sender, EventArgs e)
    
        {
    
            string command = ("insert into GeneralInfo values (@FamilyName, @FirstName, @MiddleName, @Gender, @CivilStatus, @Citizenship, @BirthPlace, @CityAddress, @CityContact, @ProvinceAddress, @ProvinceContact, @Attainment)");
    
            SqlCommand cmd = new SqlCommand(command, con);
    
            cmd.Parameters.Add("@FamilyName", SqlDbType.NVarChar).Value = familyname.Text;
    
            cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = firstname.Text;
    
            cmd.Parameters.Add("@MiddleName", SqlDbType.NVarChar).Value = middlename.Text;
    
            cmd.Parameters.Add("@Gender", SqlDbType.NVarChar).Value = gender.SelectedValue;
    
            cmd.Parameters.Add("@CivilStatus", SqlDbType.NVarChar).Value = civilstatus.SelectedValue;
    
            cmd.Parameters.Add("@Citizenship", SqlDbType.NVarChar).Value = citizenship.Text;
    
            cmd.Parameters.Add("@BirthPlace", SqlDbType.NVarChar).Value = birthplace.Text;
    
            cmd.Parameters.Add("@CityAddress", SqlDbType.NVarChar).Value = cityaddress.Text;
    
            cmd.Parameters.Add("@CityContact", SqlDbType.BigInt).Value = citycontact.Text;
    
            cmd.Parameters.Add("@ProvinceAddress", SqlDbType.NVarChar).Value = provinceaddress.Text;
    
            cmd.Parameters.Add("@ProvinceContact", SqlDbType.BigInt).Value = provincecontact.Text;
    
            string getValue="";
    		for (int i = 0; i < attainment.Items.Count; i++)
    		{
    			if (attainment.Items[i].Selected)
    				getValue += attainment.Items[i].Value + ";";
    		}
    		cmd.Parameters.Add("@Attainment",SqlDbType.NVarchar).Value=getValue;  
    
            con.Open();
    
            cmd.ExecuteNonQuery();
    
            con.Close();
    
        }

    Here i used ";" for separation


    Thursday, June 10, 2010 11:07 PM
  • User1224194097 posted

    That statement is using LINQ. you can view some examples here

    I am reading all ListItems from the CheckBoxList into a list generic and then

    filtering them with where clause to get the selected items and then

    just reading Value of the selected items and then

    creating an array of strings from that filtered list.

    so, the output will be the array of your selected values.

    and String.Join joins the array of strings with the separator that you give as the first parameter.

    so, I am getting a comma separated values of the selected array.

    It does same thing as the for each iterator but it is just in one line.

    you can view LINQ samples here at

    http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

    your button will be like this

    protected void submitButton_Click(object sender, EventArgs e)

        {

            string command = ("insert into GeneralInfo values (@FamilyName, @FirstName, @MiddleName, @Gender, @CivilStatus, @Citizenship, @BirthPlace, @CityAddress, @CityContact, @ProvinceAddress, @ProvinceContact, @Attainment)");

            SqlCommand cmd = new SqlCommand(command, con);

            cmd.Parameters.Add("@FamilyName", SqlDbType.NVarChar).Value = familyname.Text;

            cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = firstname.Text;

            cmd.Parameters.Add("@MiddleName", SqlDbType.NVarChar).Value = middlename.Text;

            cmd.Parameters.Add("@Gender", SqlDbType.NVarChar).Value = gender.SelectedValue;

            cmd.Parameters.Add("@CivilStatus", SqlDbType.NVarChar).Value = civilstatus.SelectedValue;

            cmd.Parameters.Add("@Citizenship", SqlDbType.NVarChar).Value = citizenship.Text;

            cmd.Parameters.Add("@BirthPlace", SqlDbType.NVarChar).Value = birthplace.Text;

            cmd.Parameters.Add("@CityAddress", SqlDbType.NVarChar).Value = cityaddress.Text;

            cmd.Parameters.Add("@CityContact", SqlDbType.BigInt).Value = citycontact.Text;

            cmd.Parameters.Add("@ProvinceAddress", SqlDbType.NVarChar).Value = provinceaddress.Text;

            cmd.Parameters.Add("@ProvinceContact", SqlDbType.BigInt).Value = provincecontact.Text;

            cmd.Parameters.Add("@Attainment",SqlDbType.NVarchar).Value=
                          string.Join(",",CheckBoxList1.Items.OfType<ListItem>().
                                  ToList().Where(t=>t.Selected==true). 
                                  Select(a=>a.Value). 
                                  ToArray<string>());
            con.Open();

            cmd.ExecuteNonQuery();

            con.Close();

        }

     

     

    Thursday, June 10, 2010 11:10 PM
  • User14881260 posted

    I used this


    1.       string getValue="";  
    2. for (int i = 0; i < attainment.Items.Count; i++)  
    3. {  
    4.     if (attainment.Items[i].Selected)  
    5.         getValue += attainment.Items[i].Value + ";";  
    6. }  
    7. cmd.Parameters.Add("@Attainment",SqlDbType.NVarchar).Value=getValue;  
    8. getValue = getValue.TrimEnd(',');

    Yes, it's getting more than one checked values but it doesn't remove the ',' at the end.

    Thursday, June 10, 2010 11:59 PM
  • User604186779 posted

    Yes, it's getting more than one checked values but it doesn't remove the ',' at the end.

    you are getting the value like this..after for-loop finished....,

    getvalue = "5;8;41;52;61;"

    so after the for loop you have to remove the last semicolon from the string so use this..,

    getValue = getValue.TrimEnd(';');

    then you have to pass to command

    cmd.Parameters.Add("@Attainment",SqlDbType.NVarchar).Value=getValue;

    Friday, June 11, 2010 12:05 AM
  • User-60125975 posted

    just change like below :

     string getValue="";  
     for (int i = 0; i < attainment.Items.Count; i++)  
     {  
         if (attainment.Items[i].Selected && i==0)  
             getValue += attainment.Items[i].Value ;
         else
             getValue +=";"+ attainment.Items[i].Value ;
    } 
    cmd.Parameters.Add("@Attainment",SqlDbType.NVarchar).Value=getValue;  
    


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 11, 2010 12:17 AM
  • User14881260 posted

    I just put the the trim above the parameters and it works now. Thanks for all the help, i'll look into the LINQ for sometime.


    Anyway, now I've got the values, I had this 'others specify' included and there's a textbox where the user will input the value for other attainments that is not inside the list. So what do you think is a good approach for this?


    If the user checked the 'others specify', then the attainment column at my database will have this value 'others'. Do you think it's kind of ugly?

    Friday, June 11, 2010 12:18 AM
  • User-60125975 posted

    ok. please mark as answer. which is helped you. so that others can get the answer easily... without read the whole replies.

    Friday, June 11, 2010 12:22 AM
  • User1224194097 posted

    you can just create others as another listitem I guess 

    Friday, June 11, 2010 12:23 AM
  • User14881260 posted

    Anyone who knows what approach is appropriate for my checkboxlist that has  "others specify" with a textbox near it for inputting a value?

    Friday, June 11, 2010 3:15 AM