SelectedValue which is invalid because it does not exist in the list of items

前端 未结 9 1720
孤独总比滥情好
孤独总比滥情好 2021-02-03 21:16

I encounter this problem repeatedly, and haven\'t a clue what is causing it. I get an exception in the DataBind: SelectedValue which is invalid because it does not exist i

相关标签:
9条回答
  • 2021-02-03 21:24

    Try setting listOrgs.SelectedValue = "0" after you refresh the DataSource

    At the moment you are trying to select the first item in an empty list.

    0 讨论(0)
  • 2021-02-03 21:26

    Not sure it is your case, but I had the same problem and apparently there was no explanation, then I realized doing a copy and paste on notepad of a field of database that at the beginning of the value there was a NULL.

    Curious thing was that a select joining tables was working. I deleted the row and reinserted, after was working fine.

    0 讨论(0)
  • 2021-02-03 21:27

    I kept getting this error.
    Weird thing is that before I set the datasource and rebind after deleting an item the selected index = -1.

    If I explicitly set the selectedIndex = -1; then it works and doesn't throw an error.

    So even though it was already -1 setting it to -1 stops it from erroring.

    Weird eh?

    0 讨论(0)
  • 2021-02-03 21:32

    In case you still have this problem this is how i resolved it:

    listOrgs.SelectedIndex = -1;    // Clears the SelectedIndex to avoid the exception
    listOrgs.DataSource = new Organization().DTListAll(SiteID);
    listOrgs.DataTextField = "OrganizationName"; 
    listOrgs.DataValueField = "OrganizationID"; 
    listOrgs.DataBind();            //Unless you have "listOrgs.AppendDataBoundItems = true" you don't need to clear the list
    
    0 讨论(0)
  • 2021-02-03 21:46

    Change the first two line with this :

    listOrgs.SelectedItem.Selected = false; 
    listOrgs.Items.Clear(); 
    
    0 讨论(0)
  • 2021-02-03 21:46

    @PMarques answer helped me out and did solve my problem.

    However whilst experimenting, it clicked in my head why I was gettign the error in the first place.

    I was setting the "Text" attribute thinking that it might create an encompassing label or fieldset + legend, for me (which it doesn't).

    The Text property for a list is infact the SelectedValue property for a ListControl.

    So my mistake in misinterpreting what the text property did.

    0 讨论(0)
提交回复
热议问题