问题
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