开发者

Dropdownlist filling throws error with null value

I have some code which fills a dropdownlist:

pn.DataSource = Datatbl.Tables["datalist开发者_StackOverflow中文版"];
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


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;
}


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜