views:

23

answers:

2

Hi everyone

I have some code which fills a dropdownlist:

pn.DataSource = Datatbl.Tables["datalist"];
pn.DataValueField = "partnumber";
pn.DataTextField = "partnumber";
pn.DataBind();
pn.Items.Insert(0, "");
pn.SelectedValue = ligne["pn"].ToString();

and when the value in the Database in null (""), it throws this error:

System.ArgumentOutOfRangeException: 'pn' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
A: 

I suggest that when pn is null, you default to the blank item:

pn.DataSource = Datatbl.Tables["datalist"];
pn.DataValueField = "partnumber";
pn.DataTextField = "partnumber";
pn.DataBind();
pn.Items.Insert(0, "");

if (!Convert.IsDBNull(ligne["pn"])
{
    pn.SelectedValue = ligne["pn"].ToString();
}
else
{
    pn.SelectedIndex = 0;
}
PhilPursglove
Thank you for your answer. It worked.
Galael
A: 

If your not sure you will always have a valid value then before setting the selected value you should check to see that it is a valid value:

if (pn.Items.FindByValue(ligne["pn"].ToString()) != null)
{
    pn.SelectedValue = ligne["pn"].ToString();
}
Kelsey