绑定下拉列表设置Text属性未触发异常问题排查
为什么设置DropDownList的Text属性不会触发异常?
嘿,我来帮你搞清楚这个问题!你这段代码里设置DrpLevel.Text = "777"没触发异常,根本不是Visual Studio的设置问题,是ASP.NET DropDownList控件本身的设计就是这样的~
先看你提供的代码:
try { dt = new DataTable(); dt.Columns.Add("Cnt"); for (int i = 1; i <= 10; i++) { dt.Rows.Add(i); } DrpLevel.DataTextField = "Cnt"; DrpLevel.DataValueField = "Cnt"; DrpLevel.DataSource = dt; DrpLevel.DataBind(); DrpLevel.Text = "777"; //Should cause error!! } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); }
为什么没触发异常?
DropDownList的Text属性设计很特殊:当你赋值的文本不在已绑定的选项列表中时,控件不会抛出异常,只是会把这个文本显示在控件的前端,但不会选中任何现有选项,也不会触发错误。这是WebForms控件的默认行为,和VS设置完全无关。
怎么测试失败场景?
如果你想触发异常来测试错误处理逻辑,可以换两种方式:
- 方式一:手动检查选项是否存在
先查找目标文本对应的选项,找不到就主动抛出异常:try { // 原绑定代码... var targetItem = DrpLevel.Items.FindByText("777"); if(targetItem == null) { throw new ArgumentException("指定的文本不存在于下拉列表中"); } DrpLevel.Text = "777"; } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } - 方式二:使用SelectedValue属性
SelectedValue属性的行为不同——如果赋值的值不在选项列表中,会直接抛出ArgumentException,刚好能触发你的catch块:try { // 原绑定代码... DrpLevel.SelectedValue = "777"; // 这里会触发异常! } catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); }
内容的提问来源于stack exchange,提问作者TheJoe
相关产品推荐
相关产品推荐

