Dynamic Checkboxlist in repeater, ASP.NET

2019-09-10 01:54发布

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条回答
何必那么认真
2楼-- · 2019-09-10 02:41

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;
查看更多
登录 后发表回答