检查是否已从 C# 的下拉列表中选择了值
我在 asp.net 环境中有 3 个下拉框(组合框)。 它们都是可选的,因此如果用户选择了任何内容,我将更新数据库,如果根本没有选择任何内容,我仍在用空值更新数据库。
我尝试这样做:
int? CountryId = Convert.ToInt32(ddCountries.SelectedItem.Value);
我希望如果没有选择任何内容,将在 CountryId 中插入 null,但是,它会抛出异常。
我尝试搜索 ddCountries.isSelected (或类似的东西),但它显然不存在..
那么我如何查明是否已在下拉框中进行选择? - 通过 C# 代码。
非常感谢
ps:我有一个想法 - 我将每个下拉框放在 try...catch 块中,如果出现异常,请手动将变量设置为 null..但我不确定这是最好的方法!
I have 3 dropdown boxes (combo box) in asp.net environment.
They are all optional, so if a user has selected anything, i am updating database, if nothing has been selected at all, i am still updating database with null values.
I tried to do this:
int? CountryId = Convert.ToInt32(ddCountries.SelectedItem.Value);
I was hoping that if nothing is selected null will be inserted in CountryId, but, instead its throwing an exception.
I tried to search for ddCountries.isSelected (or something like that) but it obviously doesnt exist..
so how do I find out if a selection has been made on a dropdown box? - through c# code.
Many Thanks
ps: I have a thought - i put each dropdown box in a try... catch block and if exception arises, set variables to null manually.. but I am not sure thats the best way to do it!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找
您永远不应该使用异常来控制程序流程。
You're looking for
You should never be using exceptions to control program flow.
这对我有用,假设您在
index 0
上有一个已插入的空项目。This worked for me, assuming that you have an empty item on
index 0
that you have inserted.您可以使用这个:
请注意,它是在 VB.Net 中
You can use this:
Please note that it is in VB.Net