C# DropDownList.DataSource NullReferenceException?
我通过后端CS代码获得空引用。为什么数据表为空C# DropDownList.DataSource NullReferenceException?,c#,asp.net,datatables,nullreferenceexception,C#,Asp.net,Datatables,Nullreferenceexception,我通过后端CS代码获得空引用。为什么数据表为空 <asp:TemplateField HeaderText="Frequency" ItemStyle-Width = "150" > <ItemTemplate> <asp:Label ID="Frequency" runat="server" Text='<% # Eval("frequency") %>' ></asp:Label> <asp:Dro
<asp:TemplateField HeaderText="Frequency" ItemStyle-Width = "150" >
<ItemTemplate>
<asp:Label ID="Frequency" runat="server" Text='<% # Eval("frequency") %>' ></asp:Label>
<asp:DropDownList ID="frequencydropdownlist" runat="server" Visible="false" ></asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="Addfrequencydropdownlist" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
更新必须先对网格进行数据绑定,然后才能访问网格的页脚。因此,我将使用
RowDataBound
事件填充DropDownList
:
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList Addfrequencydropdownlist = (DropDownList)e.Row.FindControl("Addfrequencydropdownlist");
// ...
}
}
旧答案(可能仍然有用):
它是
Addfrequencydropdownlist
,在您尝试强制转换后为null
,因为网格页脚中DropDownList
的NamingContainer
不是网格本身,而是FooterRow
。因此这是导致NullReferenceException
的null
:
CollectionHead_GridView.FindControl("Addfrequencydropdownlist")
您可以使用网格的名称获取其引用:
GridViewRow footer = CollectionHead_GridView.FooterRow;
DropDownList Addfrequencydropdownlist = (DropDownList)footer.FindControl("Addfrequencydropdownlist");
另一方面,只有在null
不是例外的情况下,我才会将用作
操作符。否则,您将用代码中的错误(在本例中,NullReferenceException
位于错误的位置)替换一个menainfulNullReferenceException
如果(!IsPostBack),我也会将其包装在中-如果启用了ViewState
,则检查仅在初始加载时对其进行数据绑定,而不是在每次回发时对其进行数据绑定(默认值):
有什么问题吗?它是Addfrequencydropdownlist
,在您试播后为null
。谢谢您的帮助,但我仍然在您的代码行中收到相同的错误,带有相同的null引用错误。谢谢您的帮助,它已经按预期帮助了我。
GridViewRow footer = CollectionHead_GridView.FooterRow;
DropDownList Addfrequencydropdownlist = (DropDownList)footer.FindControl("Addfrequencydropdownlist");
if(!IsPostBack)
{
DataTable dtt = new DataTable();
// rest of your code in Page_Load ....
}