-3

I have been getting the NullrefernceException on my aspx.cs page even though I already assigned a text for the label in my aspx page. At first i thought it could be the session but i log in and try i still get the same error. I have checked my database and the spelling and there is nothing wrong

My aspx.cs code:

protected void Page_Load(object sender, EventArgs e)
{
    Label Lefthowmanylabel =(Label)DataList1.FindControl("Lefthowmanylabel");
    Label quantitylabel = (Label)DataList1.FindControl("quantitylabel");


    if (int.Parse(quantitylabel.Text) < 11)
    {
        Lefthowmanylabel.Visible = true;
    }
    else
    {
        Lefthowmanylabel.Visible = false;
    }


}

My datalist item in aspx page:

<asp:Label ID="Lefthowmanylabel" runat="server"  Text="Only 10 Left!! While stock last!" Visible="False"/>
<asp:Label ID="quantitylabel" runat="server" Text='<%# Eval("Quantity") %>' Visible="False" />
                </td>
steven
  • 1
  • 3
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Owen Pauling Jan 17 '17 at 15:42
  • 2
    I strongly suggest that the first thing you do is start following .NET naming conventions. Next, note that in your `Page_Load` method you aren't assigning values to *fields* at all - you're declaring local variables and assigning values to them. – Jon Skeet Jan 17 '17 at 15:44
  • What if you remove that `quantitylabel.Text` code, how does that rendered page looks like after that? Does it have item with id `quantitylabel`? What if you log something like `Log.Write("quantitylabel is null: {0}", quantitylabel == null)` in `Page_Load` event? – alex.b Jan 17 '17 at 15:45
  • 1
    @Null nope it has nothing to do with the visible="false" – steven Jan 17 '17 at 16:00
  • @alex.b cannot work it shows Log is not in the content – steven Jan 17 '17 at 16:00
  • @steven, ok, you don't have the `Log` class... Can you print the fact if `quantitylabel ` out to somewhere else? e.g. file or console? – alex.b Jan 17 '17 at 16:13

1 Answers1

0

If you want to access access controls inside DataList and manipulate them, you want to use ItemDataBound.

For example,

<asp:DataList ... OnItemDataBound="Item_Bound"  runat="server">
</asp:DataList>

void Item_Bound(Object sender, DataListItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || 
      e.Item.ItemType == ListItemType.AlternatingItem)
   {
      Label lefthowmanylabel =(Label)e.Item.FindControl("Lefthowmanylabel");
      Label quantitylabel = (Label)e.Item.FindControl("quantitylabel");

      if (int.Parse(quantitylabel.Text) < 11)
      {
          lefthowmanylabel.Visible = true;
      }
      else
      {
         lefthowmanylabel.Visible = false;
      }
   }
}
Win
  • 56,078
  • 13
  • 92
  • 167