如何获取CheckBoxList选择的值,我所拥有的C#.NET/VisualWebPart似乎不起作用

anp*_*tel 12 html c# asp.net htmltextwriter

我在类文件中创建一个CheckBoxList,并使用HTMLTextWriter来呈现控件.

我正在使用以下代码将所选值存储在字符串中:

string YrStr = "";
for (int i = 0; i < YrChkBox.Items.Count; i++)
{
    if (YrChkBox.Items[i].Selected)
    {
        YrStr += YrChkBox.Items[i].Value + ";"; 
    }
}
Run Code Online (Sandbox Code Playgroud)

我逐步完成了代码,它似乎没有触及if语句的内部,并且每次选中的value属性都是false ...任何人都知道如何解决这个问题?

我使用以下内容填充它:

 YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
Run Code Online (Sandbox Code Playgroud)

Wal*_*alk 27

在你的ASPX页面中你有这样的列表:

    <asp:CheckBoxList ID="YrChkBox" runat="server" 
        onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
    <asp:Button ID="button" runat="server" Text="Submit" />
Run Code Online (Sandbox Code Playgroud)

在aspx.cs页面后面的代码中,你有这个:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Populate the CheckBoxList items only when it's not a postback.
            YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));
            YrChkBox.Items.Add(new ListItem("Item 2", "Item2"));
        }
    }

    protected void YrChkBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Create the list to store.
        List<String> YrStrList = new List<string>();
        // Loop through each item.
        foreach (ListItem item in YrChkBox.Items)
        {
            if (item.Selected)
            {
                // If the item is selected, add the value to the list.
                YrStrList.Add(item.Value);
            }
            else
            {
                // Item is not selected, do something else.
            }
        }
        // Join the string together using the ; delimiter.
        String YrStr = String.Join(";", YrStrList.ToArray());

        // Write to the page the value.
        Response.Write(String.Concat("Selected Items: ", YrStr));
    }
Run Code Online (Sandbox Code Playgroud)

确保您使用if (!IsPostBack) { }条件,因为如果您在每次刷新页面时加载它,它实际上会破坏数据.


Met*_*Man 5

尝试这样的事情:

foreach (ListItem listItem in YrChkBox.Items)
{
    if (listItem.Selected)
    { 
       //do some work 
    }
    else 
    { 
      //do something else 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 啊,我明白你在说什么,是的,你是对的,我没有那样做。我真的希望这能有所帮助,尽管 T_T 我遇到了同样的问题..我认为这是因为我的按钮不是服务器端 (2认同)