Question

Hello and thanks for taking your time to help me.

I'm trying to change the text of a textbox thats located inside my repeater.

<asp:Repeater runat="server" ID="rpCategories">
                        <HeaderTemplate>
                            <ul id="nav_down" class="nav_down">
                        </HeaderTemplate>
                        <ItemTemplate>
                            <li><a href="<%# Eval("ID", "/products.aspx?id={0}") %>"><%# Eval("Title") %></a></li>
                        </ItemTemplate>
                        <FooterTemplate>
                            <li><a href="#"></a></li>
                            <li><a href="#">Contact</a></li>
                            <li><a id="cart_logo"></a>
                                <asp:Panel runat="server" ID="pnlBasket">
                                    <asp:textbox runat="server" id="txtTotalCount" Enabled="false" CssClass="ltTotalCount"></asp:textbox>
                                </asp:Panel>
                            </li>
                            </ul>
                        </FooterTemplate>
                    </asp:Repeater>

It's the asp:textbox with the id="txtTotalCount" that I want to change the text of.

Here is my C# code:

TextBox ltTotalCount = (TextBox)FindControl("lblTotalCount");
ltTotalCount.Text = "1";

But if I run the code I get this error : Object reference not set to an instance of an object.

Would be so happy if someone could tell me what I'm doing wrong.

Was it helpful?

Solution 3

The ID is probably being 'enhanced' to prevent duplicate IDs in the rendered HTML. You can verify this by looking at the html.

You can add this to the textbox: ClientIDMode="Static" to make the ID stay the same.

You are getting the error because FindControl is returning a null but you are trying to access it anyway.

[Edit] Someone pointed out that this shouldn't work. I agree, here is what does work:

Control FooterTemplate = rpCategories.Controls[rpCategories.Controls.Count - 1].Controls[0];

TextBox MyTextBox = FooterTemplate.FindControl("txtTotalCount") as TextBox;

OTHER TIPS

Becuase lblTotalCount is inside a parent control - the repeater, you have to reference it through the repeater.

You should be able to just add the id of your repeater before FindControl, like this...

TextBox ltTotalCount = (TextBox)rpCategories.FindControl("lblTotalCount");

You have to specify the repeater as the parent control to look for the text box and also since it's repeater its quite possible to have more than one text box with that Id so you have to specify which repeater item to look into like so:

TextBox ltTotalCount = rpCategories.Items[0].FindControl("txtTotalCount") as TextBox;

This will return the textbox in the first row of the repeater. And you should use the Id value not the CssClass value

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top