' System.NullReferenceException'在gridview的页脚行控制

时间:2015-03-10 12:29:18

标签: c# webforms

我正在尝试在网格视图的页脚行中填充下拉列表。我的标记如下:

<asp:Label ID="lblGrdImages" runat="server" ></asp:Label>
<asp:GridView 
    ID="grdImages" 
    runat="server"
    AllowPaging="true"
    ShowFooter="true"
    PageSize="5"
    AutoGenerateColumns="false"
    OnPageIndexChanging="grdImages_PageIndexChanging"
    OnRowCancelingEdit="grdImages_RowCancelingEdit"
    OnRowCommand="grdImages_RowCommand"
    OnRowEditing="grdImages_RowEditing"
    OnRowUpdating="grdImages_RowUpdating"
    OnRowDeleting="grdImages_RowDeleting" 
    EmptyDataText="No Data Available at this Time"       >
    <AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>        


    <Columns>

        <asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
            <ItemTemplate>
                <asp:Label ID="lblProdId" runat="server" Text='<%# Eval("pi.ProductId") %>' ></asp:Label>
            </ItemTemplate>

            <EditItemTemplate>
                <asp:Label ID="lblEditProdId" runat="server" Text='<%# Eval("pi.ProductId") %>' ></asp:Label>
            </EditItemTemplate>
            <FooterTemplate>
                <asp:DropDownList ID="lstAddProdId" runat="server"  AppendDataBoundItems="true" >
                    <asp:ListItem>Select a product</asp:ListItem>
                </asp:DropDownList>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
            <ItemTemplate>
                <asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("pi.ImageId") %>' ></asp:Label>
                <asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("pi.ImagePath") %>' />
            </ItemTemplate>
            <FooterTemplate>
                <asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
            <ItemTemplate>
                <h2>repeater here</h2>
            </ItemTemplate>
            <FooterTemplate>
                <asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
            </FooterTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
                <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
                <br />
                <span onclick="return confirm('Are you sure you want to declare this product Discontinued?')">
                    <asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
                </span>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                <br />
                <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
            </EditItemTemplate>
            <FooterTemplate>
                <asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>

    <EditRowStyle BackColor="#999999"></EditRowStyle>

    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>

    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>

    <PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>

    <RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>

    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>

    <SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>

    <SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>

    <SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>

    <SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>

我的代码隐藏功能,用于填充下拉列表:

protected void lstProducts()
{
    // find dropdownlist in the footer row of the gridview
    DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
    // define ado.net objects
    SqlConnection con = new SqlConnection(connectionString);
    SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataReader reader;
    // define the sp parameters
    cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.VarChar, 50));
    cmd.Parameters["@Status"].Value = "LstProds";

    try
    {
        con.Open(); // try to connect to db.
        reader = cmd.ExecuteReader();   // execut the reader
        while (reader.Read())
        {                
            ListItem item = new ListItem(); // create listitem
            item.Text = reader["p.ProductName"].ToString();   // add product name to item text
            item.Value = reader["p.ProductId"].ToString();    // add productId to item value
            prods.Items.Add(item);    // populate dropdown list.
        }

    }
    catch (Exception err)
    {
        lblGrdImages.Text = err.Message; // display error message in  a label
    }
    finally
    {
        con.Close();    // close the connection.
    }
}

当我尝试运行它时,我收到以下错误:

  

App_Web_su5rfbqf.dll中发生了'System.NullReferenceException'类型的异常,但未在用户代码中处理

我不确定为什么我会收到这个例外。我假设它无法在网格视图页脚行中找到控件,但我不知道为什么。在某个地方可能是一个愚蠢的错误,但我无法弄清楚我应该做什么

编辑我在这行lstProducts()上收到错误:

DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");

1 个答案:

答案 0 :(得分:0)

您必须先将Datasource设置为gridView。您收到的错误位于grdImages.FooterRow=null。请先尝试填充grdImages,然后尝试访问它。

这是一个类似的例子,它做同样的

<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false" ShowFooter = "true" OnDataBound = "OnDataBound">
<Columns>
    <asp:TemplateField HeaderText = "Name">
        <ItemTemplate>
            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
        </ItemTemplate>
        <FooterTemplate>
            <asp:TextBox ID="txtName" runat="server" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText = "Country">
        <ItemTemplate>
            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Country") %>' />
        </ItemTemplate>
        <FooterTemplate>
            <asp:DropDownList ID="ddlCountries" runat="server">
            </asp:DropDownList>
        </FooterTemplate>
    </asp:TemplateField>
</Columns>

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
            dt.Rows.Add(1, "John Hammond", "United States");
            dt.Rows.Add(2, "Mudassar Khan", "India");
            dt.Rows.Add(3, "Suzanne Mathews", "France");
            dt.Rows.Add(4, "Robert Schidner", "Russia");
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

    protected void OnDataBound(object sender, EventArgs e)
    {
        DropDownList ddlCountries = GridView1.FooterRow.FindControl("ddlCountries") as DropDownList;
    }