Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DropDownList.DataSource NullReferenceException?_C#_Asp.net_Datatables_Nullreferenceexception - Fatal编程技术网

C# DropDownList.DataSource NullReferenceException?

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

我通过后端CS代码获得空引用。为什么数据表为空

<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
位于错误的位置)替换一个menainful
NullReferenceException

如果(!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 ....
}