2015-03-10 2 views
0

Я пытаюсь заполнить выпадающий список в нижнем колонтитуле сетки. моя наценка выглядит следующим образом:'System.NullReferenceException' для управления в нижнем колонтитуле gridview

<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. 
    } 
} 

Когда я пытаюсь запустить его, я получаю следующую ошибку:

An exception of type 'System.NullReferenceException' occurred in App_Web_su5rfbqf.dll but was not handled in user code

Я не уверен, почему я получаю это исключение. Я предполагаю, что он не может найти элемент управления в строке нижнего колонтитула сетки, но я не знаю почему. Это может быть глупую ошибку где-то, но я не могу понять, что я должен делать

EDIT Я получаю ошибку на этой линии lstProducts():

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

[Что такое 'NullReferenceException' и как это исправить?] (Http://stackoverflow.com/ Вопросы/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –

+0

Я получаю то, что означает исключение с нулевой ссылкой, но я не понимаю, почему это происходит в этом случае. –

+0

проверьте строку подключения и разместить точку останова, чтобы сузить задачу – Sim1

ответ

0

Вы должны установить Datasource к вашему gridView first. Ошибка, которую вы получаете, составляет 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; 
    } 
Смежные вопросы