Pedro Costa
Pedro Costa

Reputation: 437

ASP.NET find control by id

I am doing a simple web site using asp.net and i am having troubles finding my or objects by id in the code behind in c#. I have something like this:

<asp:ListView ID="InternamentosListView" runat="server"
            DataSourceID="InternamentosBD">
        <LayoutTemplate>
            <table id="camas">

                    <asp:PlaceHolder runat="server" ID="TablePlaceHolder"></asp:PlaceHolder>

            </table>

        </LayoutTemplate>

the rest is irrelevant, and then i use this in the code behind:

Table table = (Table)FindControl("camas");

i also tried:

Table table = (Table)camas;

and

Control table= (Table)FindControl("camas");

and each one of this lines gives me Null. am i doing something wrong ?

EDIT: From your answers i did this:

<LayoutTemplate>

            <table id="camas" runat="server">


            </table>

        </LayoutTemplate>

and tried all the things stated above. same result.

EDIT2: Whole Code:

C#

 protected void Page_Load(object sender, EventArgs e)
    {

        Table table = (Table)FindControl("camas");
        HiddenField NCamasHF = (HiddenField)FindControl("NCamas");
        int NCamas = Convert.ToInt32(NCamasHF);
        HiddenField NColunasHF = (HiddenField)FindControl("NColunas");
        HiddenField CorMasc = (HiddenField)FindControl("CorMasc");
        HiddenField CorFem = (HiddenField)FindControl("CorFem");
        int NColunas = Convert.ToInt32(NColunasHF);
        TableRow Firstrow = new TableRow();
        table.Rows.Add(Firstrow);
        for (int i = 1; i <= NCamas; i++)
        {
            if (i % NColunas == 0)
            {
                TableRow row = new TableRow();
                table.Rows.Add(row);
                TableCell cell = new TableCell();
                cell.BackColor = System.Drawing.Color.LightGreen;
                cell.CssClass = "celula";
                row.Cells.Add(cell);
            }
            else
            {
                TableCell cell = new TableCell();
                cell.BackColor = System.Drawing.Color.LightGreen;
                cell.CssClass = "celula";
                Firstrow.Cells.Add(cell);
            }
        }
    }

asp.net

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

     <asp:SqlDataSource
        ID="ParametrosBD"
        ConnectionString ="<%$ ConnectionStrings:principal %>"
        ProviderName = "System.Data.SqlClient"
        SelectCommand = "SELECT par_Id, par_NCamas, par_NColunas, par_CorMasculino, par_CorFeminino FROM Parametros WHERE par_Id=1"
        runat="server">
       </asp:SqlDataSource>
    <asp:ListView ID="InternamentosListView" runat="server"
            DataSourceID="InternamentosBD">
        <LayoutTemplate>

            <table id="camas" runat="server">


            </table>

        </LayoutTemplate>
        <ItemTemplate>
            <asp:HiddenField ID="NCamas" runat="server" Value='<%# Bind("par_NCamas") %>' />
            <asp:HiddenField ID="NColunas" runat="server" Value='<%# Bind("par_NColunas") %>' />
            <asp:HiddenField ID="CorMasc" runat="server" Value='<%# Bind("par_CorMasculino") %>' />
            <asp:HiddenField ID="CorFem" runat="server" Value='<%# Bind("par_CorFeminino") %>' />
            <tr id="cama"></tr>
            </ItemTemplate>
    </asp:ListView>

</asp:Content>

Upvotes: 3

Views: 37265

Answers (8)

user2126738
user2126738

Reputation: 21

as this post will also show up when searching for ASP.NET and VB.NET, the recurcive itteration will also work here.

Private Function FindUsercontrol(ByVal ucs As Control, ID As String) As Control

    If ucs.ID = ID Then Return ucs
    For Each uc In ucs.Controls
        If uc.ID = ID Then Return uc
        Dim userControls = FindUsercontrol(uc, ID)
        If userControls IsNot Nothing Then Return userControls
    Next

End Function

and can be called with uc = FindUsercontrol(Page.Controls(0), "ID") the control with the ID is returned.

Upvotes: 0

GreySage
GreySage

Reputation: 1182

None of the existing answers mention the obvious built-in solution, FindControl.

Detailed here, FindControl is a function that takes as a string the id of a control that is a child of the calling Control, returning it if it exists or null if it doesn't.

The cool thing is that you can always call it from the Page control which will look through all controls in the page. See below for an example.

var myTextboxControl = (TextBox)Page.FindControl("myTextboxControlID);
if (myTextboxControl != null) {
    myTextboxControl.Text = "Something";
}

Note that the returned object is a generic Control, so you'll need to cast it before you can use specific features like .Text above.

Upvotes: 2

Michael Goldshmidt
Michael Goldshmidt

Reputation: 141

You need to add runat server like previously stated, but the ID will change based on ListView row. You can add clientidmode="Static" to your table if you expect only 1 table and find using InternamentosListView.FindControl("camas"); otherwise, you will need to add ItemDataBound event.

<asp:ListView ID="InternamentosListView" runat="server"         DataSourceID="InternamentosBD" OnItemDataBound="InternamentosListView_ItemDataBound">
        <LayoutTemplate>
            <table id="camas">
<asp:PlaceHolder runat="server" ID="TablePlaceHolder"></asp:PlaceHolder>
</table>
</LayoutTemplate>

You will need to introduce in code behind

InternamentosListView_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Table tdcamas = (Table)e.Item.FindControl("camas");
            }
}

Upvotes: 0

Benny
Benny

Reputation: 53

When you're using a master page, then this code should work for you

Note that you're looking for htmlTable and not asp:Table.

// add the namespace

using System.Web.UI.HtmlControls;

// change the name of the place holder to the one you're using

HtmlTable tbl = this.Master.FindControl("ContentPlaceHolder1").FindControl("camas") as HtmlTable;

Best, Benny

Upvotes: 0

user4457732
user4457732

Reputation:

To expand on @Yura Zaletskyy's recursive find control method from MSDN -- you can also use the Page itself as the containing control to begin your recursive search for that elusive table control (which can be maddening, I know, I've been there.) Here is a bit more direction which may help.

using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI;

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Table table = (Table)FindControlRecursive(Page, "camas");
        if (table != null)
        {
            //Do awesome things.
        }
    }

    private Control FindControlRecursive(Control rootControl, string controlID)
    {
        if (rootControl.ID == controlID) return rootControl;

        foreach (Control controlToSearch in rootControl.Controls)
        {
            Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
            if (controlToReturn != null) return controlToReturn;
        }
        return null;
    }
}

Upvotes: 8

Yuriy Zaletskyy
Yuriy Zaletskyy

Reputation: 5151

As you already added runat="server" is step 1. The second step is to find control by id, but you need to do it recursively. For example consider following function:

private Control FindControlRecursive(Control rootControl, string controlID)
{
    if (rootControl.ID == controlID) return rootControl;

    foreach (Control controlToSearch in rootControl.Controls)
    {
        Control controlToReturn = 
            FindControlRecursive(controlToSearch, controlID);
        if (controlToReturn != null) return controlToReturn;
    }
    return null;
}

Upvotes: 4

stripathi
stripathi

Reputation: 786

Ok. You have the table within a list view template. You will never find the control directly on server side. What you need to do is find control within the items of list.Items array or within the item data bound event.

Take a look at this one- how to find control in ItemTemplate of the ListView from code behind of the usercontrol page?

Upvotes: 0

Fishcake
Fishcake

Reputation: 10754

You need to have runat="server" for you to be able to see it in the codebehind.

e.g.

<table id="camas" runat="server">

Upvotes: 0

Related Questions