0

I have encountered this error "Object reference not set to an instance of an object." when i trying to set a value which i had session from the previous page and set it on a template field. when I debugged it, the session value was there(successfully session over). what i am trying to do is to display the value of what I had session on detailsview.

aspx :

 <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False">

    <Fields>
        <asp:TemplateField HeaderText="Order Number " SortExpression="poNum">

            <ItemTemplate>
                <asp:Label ID="test" runat="server" Text='<%# Bind("poNum") %>'></asp:Label>
            </ItemTemplate>

        </asp:TemplateField>

       </Fields>
    </asp:DetailsView>

code behind :

  protected void Page_Load(object sender, EventArgs e)
  {

    ((Label)DetailsView1.FindControl("test")).Text = Session["poNum"].ToString();
   } 

I was wondering why I was unable to get the control from detailsview??

EDIT

    Label aaa = new Label();
    aaa.Text = Session["poNum"].ToString();

    Label orderNum = (Label)DetailsView1.FindControl("test"); // orderNum was null here 
    orderNum.Text = aaa.Text; 
user1501969
  • 127
  • 7
  • 17

2 Answers2

1

You can access the Label in DataBound event of DetailsView.

Memoizer
  • 2,231
  • 1
  • 14
  • 14
  • but, i want to set the session value to detailsview when the page is loading. I had tried this before, but the code did not run the databound event. – user1501969 Jan 19 '13 at 13:25
  • It is fundamentally? Why don't you just bind session value to DetailsView? – Memoizer Jan 19 '13 at 13:32
  • Yes, i know where the problems lies now. The error would occur because I did not bind it ? After I tried to bind the Detailsview to an objectdatesource, the error was solved. Thanks! – user1501969 Jan 19 '13 at 13:35
0

Are you calling FindControl before data binding the DetailsView? If so, it will return null - nothing there to find yet.

Ray
  • 21,485
  • 5
  • 48
  • 64