Asp.net下拉列表源有值,但抛出空异常
本文关键字:异常 net 下拉列表 Asp | 更新日期: 2023-09-27 18:02:56
当逐步执行代码时,它在"fUserSelect"行失败,说"对象引用未设置为对象的实例",但arrUsers显然是填充的,所以我在这里感到困惑。
任何额外的眼睛在这将是美妙的!
Aspx设置:
<label for="fUser">User<span class="tip required">*</span></label>
<div class="group">
<span class="data dropdown">
<asp:DropDownList runat="server" ID="fUserSelect" EnableViewState="false"/>
</span>
</div>
CS: List<KeyValuePair<string, string>> arrUsers = new List<KeyValuePair<string, string>>(){
new KeyValuePair<string, string>("1", "Test"),
new KeyValuePair<string, string>("2", "Test2")
};
fUserSelect.DataValueField = "Key";
fUserSelect.DataTextField = "Value";
fUserSelect.DataSource = arrUsers;
fUserSelect.SelectedIndex = 0;
fUserSelect.DataBind();
我使用下面的代码绑定DropdownList
使用Dictionary
对象。请参考以下代码:
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("item 1", "Item 1");
list.Add("item 2", "Item 2");
list.Add("item 3", "Item 3");
list.Add("item 4", "Item 4");
ddl.DataSource = list;
ddl.DataTextField = "Value";
ddl.DataValueField = "Key";
ddl.DataBind();
我希望它能帮助你。
如果你想遵循你的代码,那么你必须先绑定DataSource
,然后再绑定DataTextField
和DataValueField
。
修改代码如下:
List<KeyValuePair<string, string>> arrUsers = new List<KeyValuePair<string, string>>(){
new KeyValuePair<string, string>("1", "Test"),
new KeyValuePair<string, string>("2", "Test2")
};
fUserSelect.DataSource = arrUsers;
fUserSelect.DataValueField = "Key";
fUserSelect.DataTextField = "Value";
fUserSelect.SelectedIndex = 0;
fUserSelect.DataBind();
谢谢。
快乐编码
在我的@ page声明中发现,我的Inherits =" control page name"引用了另一个控件。原来是复制粘贴错误。这个问题/答案帮助我解决了问题。
我张贴这作为我的答案,但我也做了一个新的实例的页面加载上的控件,我最终给我的控件一个ID名称,并使用它作为参考,而不是看它的一个新的实例。