c# - 如何获取复选框列表控件中的选中项

标签 c# asp.net checkboxlist

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

这是我的数据绑定(bind)代码:

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

现在我的概率是我正在获取项目的名称,但无论选择如何,所选择的属性都是错误的

致谢

最佳答案

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

if (!IsPostBack)

关于c# - 如何获取复选框列表控件中的选中项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5013755/

相关文章:

asp.net - 文本框数据绑定(bind)

javascript - 当每个属性的值是动态的时,如何使用 JavaScript 验证所需的复选框列表?

c# - 清除 CheckBoxList 的值?

jquery - 自动前进到 HTML 表单中的下一个字段,而不更改选项卡行为

php - 如何使用ajax加载checkboxList

c# - Linq Getting Customers 按日期分组,然后按类型分组

c# - 服务堆栈 : Attributes for indexes not working?

c# - 创建一个新的 MailAddress 会产生 "The specified string is not in the form required for an e-mail address",尽管它的格式是正确的

c# - C#中的无锁 session 是什么?

C# 导出列格式不正确的 csv (Excel)