gpt4 book ai didi

c# - 我怎样才能得到 CheckBoxList 选定的值,我所拥有的似乎不起作用 C#.NET/VisualWebPart

转载 作者:技术小花猫 更新时间:2023-10-29 12:36:02 25 4
gpt4 key购买 nike

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

我使用以下代码将选定的值存储在一个字符串中:

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

我单步执行了代码,它似乎并没有触及 if 语句的内部,并且每次选择的值属性都是 false ...任何人都知道我该如何解决这个问题?

我使用以下内容填充它:

 YrChkBox.Items.Add(new ListItem("Item 1", "Item1"));

最佳答案

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

    <asp:CheckBoxList ID="YrChkBox" runat="server" 
onselectedindexchanged="YrChkBox_SelectedIndexChanged"></asp:CheckBoxList>
<asp:Button ID="button" runat="server" Text="Submit" />

在您的 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));
}

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

关于c# - 我怎样才能得到 CheckBoxList 选定的值,我所拥有的似乎不起作用 C#.NET/VisualWebPart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9523263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com