2015-11-26 78 views
1

本人曾经形式此CheckBoxList加入aspx页面数据库中存储的值:禁用和检查的`CheckBoxList`在C#

<asp:CheckBoxList ID="Fruits" runat="server"> 
    <asp:ListItem Text="Mango" Value="1" /> 
    <asp:ListItem Text="Apple" Value="2" /> 
    <asp:ListItem Text="Banana" Value="3" /> 
    <asp:ListItem Text="Guava" Value="4" /> 
    <asp:ListItem Text="Orange" Value="5" /> 
</asp:CheckBoxList> 

enter image description here

在这种CheckBoxList有可能选择多个值,例如:

enter image description here

而这个值在数据库表中的字段存储:

for (int i = 0; i < Fruits.Items.Count; i++) 
{ 
    if (Fruits.Items[i].Selected == true) 
    { 
     FruitsUpdate += Fruits.Items[i].Text.ToString() + ";"; 
    } 
} 

值在数据库中存储:1;4;5;

现在,在ASPX表单页面,我需要禁用和检查值的CheckBoxList记忆在数据库中,但我已经尝试过这段代码,但没有成功,因为所有ListItem都被禁用但未被检查。

FruitsDB = dr["Fruits"].ToString(); 

if (FruitsDB.ToString() != "") 
{ 
    Fruits.Text = FruitsDB.ToString(); 
    Fruits.Enabled = false; 
} 
else 
{ 
    Fruits.Enabled = true; 
} 

我需要禁用,并在检查的CheckBoxList与价值的物品1和4和5

请帮帮我,谢谢你提前。

+0

在代码的第二部分,您没有选择任何内容,只是将checkedlistbox设置为启用或禁用。 FruitsDB返回什么? –

+0

@PauloLima谢谢。 'FruitsDB'的返回值是'1; 4; 5;' –

+0

@PauloLima:我需要禁用并在CheckBoxList中检查值为“1; 4; 5;' –

回答

0

您没有设置设置Enabled属性的列表项的Selected属性。

这是代码。你将迭代CheckBoxList。如果当前复选框的值在FruitsDB中,那么它将被选中并禁用。

var memory = FruitsDB.ToString(); 

    foreach (ListItem item in Fruits.Items) 
    { 
     if (memory.Contains(item.Value)) 
     { 
      item.Enabled = false; 
      item.Selected = true; 
     } 
    } 
+0

谢谢,但我不明白你的回复;我需要禁用并在CheckBoxList中检查值为1; 4; 5;的项目 –

相关问题