下拉列表填充会抛出空值错误
我有一些填充下拉列表的代码:
pn.DataSource = Datatbl.Tables["datalist"];
pn.DataValueField = "partnumber";
pn.DataTextField = "partnumber";
pn.DataBind();
pn.Items.Insert(0, "");
pn.SelectedValue = ligne["pn"].ToString();
当数据库中的值为空(“”)时,它会抛出此错误:
System.ArgumentOutOfRangeException: 'pn' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议当pn为null时,默认为空白项:
I suggest that when pn is null, you default to the blank item:
如果您不确定您将始终拥有一个有效值,那么在设置所选值之前,您应该检查它是否是一个有效值:
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: