how to get the selected items in the checkboxlist control

4.9k Views Asked by At

I am using 2 checkboxlist controls namely chklstearnings,chklstdeductions in my .aspx page and am binding the data to the checkbox list using a dataset. Now when I try to get the selected items am unable to do so.

Here is my code for data binding:

page_load
{

   MySqlConnection con= new MySqlConnection(System.Configuration.ConfigurationSettings.AppSettings.Get("connectionString"));
   MySqlCommand com=con.CreateCommand();
   com.CommandText="select earningordeductiondescription,earningordeductioncode from tblearninganddeduction where earningordeductioncode between 1000 and 1999";
   com.CommandType=CommandType.Text;
   DataSet ds=new DataSet();
   MySqlDataAdapter da=new MySqlDataAdapter();
   da.SelectCommand=com;
   da.Fill(ds,"earnings");
   chklstEarnings.DataSource=ds.Tables["earnings"];
   chklstEarnings.DataTextField = "earningordeductiondescription";
   chklstEarnings.DataValueField="earningordeductioncode";
   chklstEarnings.DataBind();
   MySqlCommand com1 = con.CreateCommand();
   com1.CommandText = "select earningordeductiondescription,earningordeductioncode from tblearninganddeduction where earningordeductioncode between 2000 and 2999";
   com1.CommandType = CommandType.Text;       
   da.SelectCommand = com1;
   da.Fill(ds, "deductions");
   chklstdeductions.DataSource = ds.Tables["deductions"];
   chklstdeductions.DataTextField = "earningordeductiondescription";
   chklstdeductions.DataValueField = "earningordeductioncode";
   chklstdeductions.DataBind();
}

Code in button click for selected items:

protected void btnsubmit_Click(object sender, EventArgs e)
{
   foreach  (ListItem ear in chklstEarnings.Items)
   {
      if (ear.Selected)
      {
         //save the earning prefarences
      }

   }

   foreach (ListItem ded in chklstdeductions.Items)
   {
      if (ded.Selected)
      {
         //save the deduction prefarences
      }
   }
}

now my prob is i am getting the name of the item in ded and ear but the property selected is all ways showing false irrespect of selection

Thanks in adv

4

There are 4 best solutions below

0
On

The Checkbox are bound again since you have not put IsPostBack part, so it will be bound again and your selection will be lost

0
On

Check IsPostBack in your page load. Because when you are clicking the button it is reloading the page.

0
On

Try by writing your code in page load by

if (!IsPostBack)
0
On

Set isPostBack property of your checkboxlist as true. and write code to get selected items from checkbox list in the selectedindexchanged event of your check box list if you want to perform some task as soon as you select some Item from your checkbox list. Thank you.