Dynamic Checkboxlist in repeater, ASP.NET

一个人想着一个人 提交于 2019-12-12 03:33:27

问题


I have a CheckBoxList in a Repeater and the code I have is from here Dynamic dropdownlist in repeater, ASP.NET.

If do this:

<asp:CheckBoxList ID="chklWorkType" runat="server" OnDataBinding="chklWorkType_DataBinding"></asp:CheckBoxList>


protected void chklWorkType_DataBinding(object sender, System.EventArgs e)
{
    CheckBoxList chk = (CheckBoxList)(sender);

    chk.Items.Add(new ListItem("nem 1", "1"));
    chk.Items.Add(new ListItem("num 2", "2"));

    chk.SelectedValue = chk.DataValueField;
}

This is my error message:

System.ArgumentOutOfRangeException: 'chklWorkType' has a SelectedValue which is invalid because it does not exist in the list of items.


回答1:


DataValueField gets or sets the field of the data source that provides the value of each list item. So normally the name of a column or something like that. But you are using this name as SelectedValue which doesn't exist because you haven't assingned one, so it's String.Empty.

You could use this, if you want the first item to be selected:

chk.SelectedValue = "1";

That's the value of the first ListItem(new ListItem("nem 1", "1")).

Of course you could also use the SelectedIndex:

chk.SelectedIndex = 0;


来源:https://stackoverflow.com/questions/35064939/dynamic-checkboxlist-in-repeater-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!