使用FOR循环返回下拉列表的SelectedValue
本文关键字:SelectedValue 下拉列表 返回 FOR 循环 使用 | 更新日期: 2023-09-27 18:18:26
我花了很多时间寻找一个看似简单的事情的解决方案。
返回"Object reference not set to an Object instance ."错误。我将此代码放在单独的空白页上以进行故障排除。什么好主意吗?
ASP。净:
<div>
<asp:DropDownList ID="ChoosePattern1" ClientIDMode="Static" runat="server" CssClass="dropformat"
AutoPostBack="true" OnSelectedIndexChanged="getimage">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ChoosePattern2" ClientIDMode="Static" runat="server" CssClass="dropformat"
AutoPostBack="true" OnSelectedIndexChanged="getimage">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
</div>
c#后台代码:protected void getimage(object sender, EventArgs e)
{
for (int intCounter = 1; intCounter <= 8; intCounter++)
{
string mypattern = "ChoosePattern" + Convert.ToString(intCounter);
DropDownList ddl = Page.FindControl(mypattern) as DropDownList;
Response.Write(ddl.SelectedValue);
}
}
这个错误信息就是所谓的"Null Reference Exception"。它通常意味着你试图访问一个对象的属性,但是这个对象是空的。
在您的情况下,ddl
可能是问题所在。如果Page.FindControl
没有找到它(或者返回的对象不是DropDownList
),则存储的值将为空。因此,访问SelectedValue
将导致异常。
您正在请求ChoosePattern1…ChoosePattern8项,但在页面上只有ChoosePattern1和ChoosePattern2存在。所以对于
DropDownList ddl = Page.FindControl("ChoosePattern3") as DropDownList;
你得到null,因为这样的ID下拉列表不存在
变化
for (int intCounter = 1;intCounter <= 8;intCounter + +)
for (int intCounter = 1;intCounter <= 2;intCounter + +)