Rahul
Rahul

Reputation: 27

Access Label control inside the detailsview control

I am trying to set the text of the label control which is inside detailsview but it's not working. But it's showing error "Object reference not set to an instance of an object." can anyone guide me please.. ?? My front end code is:

<asp:Panel ID="sub_question_panel" runat="server">
   <asp:DetailsView ID="DetailsView1" runat="server" CellPadding="6"    ForeColor="#333333" AutoGenerateRows="false" GridLines="None" >
   <Fields>
      <asp:TemplateField>
         <ItemTemplate>
               <table id="Question_view_table">
                  <tr>
<td style="font-family:Arial Rounded MT;">
<label id="Question_no"><span style="font-size:20px;">Question</span>:</label>
<asp:Label ID="Ques_id_label" runat="server" Text="Label"></asp:Label></td>
</tr>
<tr>
<td style="height:20px"></td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px; ">
<label id="Question_detail"><%# Eval ("Question") %></label>
</td>
</tr>
<tr>
<td style="font-family:'Times New Roman'; font-size:18px;">
<ol style="list-style:upper-alpha">
<li>
<label id="optn1"> &nbsp&nbsp<%# Eval ("Option1") %></label></li>
<li>
<label id="optn2"> &nbsp&nbsp<%# Eval ("Option2") %></label></li>
<li>
<label id="optn3"> &nbsp&nbsp<%# Eval ("Option3") %></label></li>
<li>
<label id="optn4"> &nbsp&nbsp<%# Eval ("Option4") %></label></li>
</ol>
</td>
</tr>
            </table>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
</asp:Panel>

My back end code is:

protected void Page_Load(object sender, EventArgs e)
{
      int question_id = 1;
      Label Question_Id = DetailsView1.FindControl("Ques_id_label") as Label;
      Question_Id .Text = Convert.ToString(question_id);
} 

Upvotes: 0

Views: 620

Answers (2)

Farzin Kanzi
Farzin Kanzi

Reputation: 3435

You must use the FindControl for a row, not DataListView

You want to find your label by id, But which one? For each row you have a label with id 'Ques_id_label' . So to find a specific label you must specify the intended row. I did not work with DataLisView but I know that it is logically similar to Asp:Repeater . To find a control in a row of a Repeater when a command is sent from a row:

protected void SaveAnswer(Object Sender, RepeaterCommandEventArgs e)
{
    Label Ques_id_label = (Label)e.Item.FindControl("Ques_id_label");

Which with e.item you specify the intended row.

Upvotes: 0

VDWWD
VDWWD

Reputation: 35524

You use FindControl to find Ques_id_label, but then reference it normally anyway: Ques_id_label.Text =

It should be Question_Id.Text = Convert.ToString(question_id);, with the ID you assigned with FindControl.

But did it even compile? Do you use an editor like Visual Studio? Because when I tried your snippet it gave the error The name 'Ques_id_label' does not exist in the current context, as it is supposed to.

Upvotes: 0

Related Questions