对象引用未设置为label对象的实例

本文关键字:对象 实例 label 设置 对象引用 | 更新日期: 2023-09-27 18:02:23

我试图在gridviewRowDataBound事件上设置gridview中的标签文本。相同的代码如下:

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int day = Convert.ToInt32(DropDownList3.SelectedValue);
        int days = System.DateTime.DaysInMonth(2013,day);
        Label lab = (Label)e.Row.FindControl("d");
        lab.Text = days.ToString();
    }
}
GRIDVIEW结构:

<asp:GridView ID="GridView2" runat="server" OnRowDataBound="GridView2_RowDataBound" />
                <asp:BoundField DataField="name" HeaderText="Name" SortExpression="n" />
                <asp:BoundField DataField="dept" HeaderText="Department" SortExpression="d" />
                <asp:BoundField DataField="code" HeaderText="Employee Code" SortExpression="c" />
                <asp:TemplateField HeaderText="Total days" >
                <itemtemplate>
                    <asp:Label ID="d" runat="server" Text="" />
                </itemtemplate>
                </asp:TemplateField>
                </asp:GridView>

在上面的代码中,'d'是gridview中标签的id。在突出显示的行,我得到错误,OBJECT REFERENCE NOT SET TO INSTANCE OF AN OBJECT.据我所知,新的标签没有被创建。那么如何分配值在这个事件中计算gridview的标签?

对象引用未设置为label对象的实例

 <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView2_RowDataBound">
        <Columns>
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="n" />
            <asp:BoundField DataField="ID" HeaderText="Department" />
            <asp:BoundField DataField="Seats" HeaderText="Employee Code" />
            <asp:TemplateField HeaderText="Total days">
                <ItemTemplate>
                    <asp:Label ID="d" runat="server" Text=""></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

哪里是你的columns标签,放入columns标签并尝试