Click here to Skip to main content
15,923,376 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am quite new with ASP.net. I created a public class within a page that has a public function that will find a control in the page, once it finds that control it converts the control to a dropdownlist and gets the text value. i used the Page.FindControl() but it always returns a null value. Here is my code:

C#
public class Dashboard : System.Web.UI.Page
    {

        public String getTxt(string xID,String xType)
        {
            String ObjText;

            switch (xType.ToUpper())
            {
                case "DROPDOWNLIST":
                    //foreach (Control c in Page.Controls)
                    //{
                    //    if (c.ID == xID)
                    //    {

                    //    }
                    //}

                    DropDownList dlist = (DropDownList) Page.FindControl(xID);

                    if (dlist != null)
                        ObjText = dlist.Text;
                    else
                        ObjText = "";
                    break;
                default:
                    ObjText = "";
                    break;
            }


            return ObjText;
        }
    }


Any help is greatly appreciated.

Thanks,
Posted
Comments
Christian Amado 8-Aug-12 15:44pm    
Why you don't simply call the dropdownlist or any control for its name (ID)? It's more easy and fast.
Franco Cipriano 9-Aug-12 8:55am    
Hi,

I tried doing that but it gives me an error object not set to an instance. I declared a new instance for the class with the control as it's member.

Thanks,
Franco Cipriano 8-Aug-12 16:16pm    
Im accessing this public function from a class, I can't access the controls from another class so I made a public class from form1 that will access the controls from form1 so that I can use it at the Class that I created.

Thanks
Franco Cipriano 8-Aug-12 16:20pm    
I was able to make the control public by declaring it public from the aspx.designer page.this got what I need, but will still try the previous approach I was thinking of
Franco Cipriano 8-Aug-12 16:28pm    
I was wrong it did not give me the text value I need, it still give NULL value.

1 solution

FindControl only goes 1 level deep in its search, so if the control you are looking for isn't directly below page level, it will return null. A recursive FindControl method (there are many online, here is one: http://weblogs.asp.net/eporter/archive/2007/02/24/asp-net-findcontrol-recursive-with-generics.aspx[^]) will help you if this is the route you want to go.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900