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.
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 asSelectedValue
which doesn't exist because you haven't assingned one, so it'sString.Empty
.You could use this, if you want the first item to be selected:
That's the value of the first
ListItem
(new ListItem("nem 1", "1")
).Of course you could also use the
SelectedIndex
: