Skip to main content
 首页 » 编程设计

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

2024年02月23日15xxx_UU

我在我的 .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)