简体   繁体   中英

how to get the selected items in the checkboxlist control

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

尝试在页面加载中编写代码

if (!IsPostBack)

复选框再次绑定,因为你还没有放入IsPostBack部分,所以它将再次绑定,你的选择将会丢失

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM