如何在checkboxlist控件中获取所选项目

时间:2011-02-16 07:43:01

标签: c# asp.net checkboxlist

我在我的.aspx中使用了2个checkboxlist控件,即chklstearnings,chklstdeductions 页面并使用数据集将数据绑定到复选框列表。现在,当我尝试获取所选项目时,我无法这样做。

这是我的数据绑定代码:

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();
}

按钮单击所选项目的代码:

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
      }
   }
}

现在我的问题是我在ded和ear中获得该项目的名称,但所选择的属性是显示错误选择的所有方式

先谢谢

4 个答案:

答案 0 :(得分:2)

尝试通过

在页面加载中编写代码
if (!IsPostBack)

答案 1 :(得分:1)

复选框再次绑定,因为您没有放置IsPostBack部分,因此它将再次绑定,您的选择将会丢失

答案 2 :(得分:1)

检查页面加载中的IsPostBack。因为当您点击按钮时,它正在重新加载页面。

答案 3 :(得分:0)

将checkboxlist的isPostBack属性设置为true。如果要在复选框列表中选择某个项目后立即执行某项任务,请编写代码以从复选框列表的selectedindexchanged事件中的复选框列表中获取所选项目。谢谢。