locked
UserControls and Code Behind + Using function from an other class RRS feed

  • Question

  • User1571226316 posted

    Hello.

    I have two smal questions.

    Is it possible to use the controls of my usercontrols pages (ascx) in the code behind ? Or in need to declare them and find them with the function FindControl() ?

     

    My second question is about linked 2 classes. I create a class and put in my functions. I want to call function of the tool class from the code behind of my usercontrols (.ascx.cs). How do that ?

     

    Thanks for answer

    Regards

    Wednesday, May 28, 2008 6:50 AM

Answers

  • User-1399914977 posted

    For point 1 you can do following

    1. By Default controls access modifiers are protected. So you have to change Text box access modifier to public.

       Personally I wont recommend that, so better to use get set properties.

      In user control define a public property

      lets say

     public string Name

    {

        get {    return TextBox1.Text; }

      set { TextBox1.Text = value; }
    }

    Now in aspx page .

    Call like this

    label1.Text = MyUserControlName.Name;

    MyUserControlName.Name  = "worldclascoders";

    --------------------------------------- sounds too simple -----------------------

    On Point 2 

     

     Make a class

    namespace Utilities {

    public class Tool()

    {

        public static string DoSomething()

        {

             /// code fires wow...
        }

       }


    }

    Inside user control  

    using Utilities;  // add namespace

    in page load or inside any event make a call

     string x  = Tool. DoSomething();

     

     

     

     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 28, 2008 8:11 AM
  • User853727733 posted

    The user controls work just like regular controls. If your control is within a container like a FormView you need to use the FindControl method of the FormView to get the control, if not you can reference the control directly.

    To use a custom class in a web application such class must be created in the App_Code folder of your website. If it's there you can call it like any other class of the framework.

    I have a post in my blog about user controls that's not specifically about what you want but will show a web control being referenced from the code behind, you can take a look at it if you want:

    http://www.gbogea.com/2008/5/17/exposing-events-in-web-user-controls/ 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 28, 2008 8:48 AM
  • User853727733 posted

    Don't worry programming is my work and my hobby! Just change you code to:

    16       protected DropDownList ddlAffaire;

    17  
    18       protected void ddlAffair_SelectedIndexChanged(object sender, EventArgs e)
    19       {

                   ddlAffaire = (DropDownList)FindControl("ddlAffair");

    20           if (ddlAffair.SelectedValue != "Select the affair")
    21           {
    22               sQuery = "SELECT designationTower, id_Tower FROM affair a " +
    23                   "JOIN poste p on a.idaffair= p.affair_idaffair " +
    24                   "JOIN team t on p.team_idteam= t.idteam " +
    25                   "JOIN tower tow on t.tower_id_tower= tow.id_tower where idaffair = '" + ddlAffair.SelectedValue + "'";
    26               ddlTower.Items.Clear();
    27               Tool.fillDropDownList("", sQuery, "ddlTower");
    28               ddlTower.Items.Add("Select the tower");
    29               ddlTower.SelectedValue = "Select the tower";
    30               displayControls(true, true, false, false, false, false);
    31           }
    32           else
    33           {
    34               displayControls(true, false, false, false, false, false);
    35           }
    36       }

    I think it should work now.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 29, 2008 9:54 AM
  • User853727733 posted

    You can change the paramter of the method to receive a Control instead of Page, so you can pass a page instance or a user control.

          public static void fillDropDownList(String sConnectionString, String sQuery, String sListName, Control control)
            {
                System.Data.OleDb.OleDbConnection conn = connect(sConnectionString);
                System.Data.OleDb.OleDbDataReader reader = executeQuery(sQuery, conn);


                DropDownList ddl = (DropDownList)control.FindControl(sListName);
                ddl.DataSource = reader;
                ddl.DataBind();


                deconnect(conn);

            }

    Using it like this you can pass a page or a control:

    fillDropDownList(myConnectionString, myQuery, myListName, this.Page)

    or

    fillDropDownList(myConnectionString, myQuery, myListName, myUserControl)

    I think it will work.


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 30, 2008 4:28 PM

All replies

  • User-1399914977 posted

    For point 1 you can do following

    1. By Default controls access modifiers are protected. So you have to change Text box access modifier to public.

       Personally I wont recommend that, so better to use get set properties.

      In user control define a public property

      lets say

     public string Name

    {

        get {    return TextBox1.Text; }

      set { TextBox1.Text = value; }
    }

    Now in aspx page .

    Call like this

    label1.Text = MyUserControlName.Name;

    MyUserControlName.Name  = "worldclascoders";

    --------------------------------------- sounds too simple -----------------------

    On Point 2 

     

     Make a class

    namespace Utilities {

    public class Tool()

    {

        public static string DoSomething()

        {

             /// code fires wow...
        }

       }


    }

    Inside user control  

    using Utilities;  // add namespace

    in page load or inside any event make a call

     string x  = Tool. DoSomething();

     

     

     

     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 28, 2008 8:11 AM
  • User853727733 posted

    The user controls work just like regular controls. If your control is within a container like a FormView you need to use the FindControl method of the FormView to get the control, if not you can reference the control directly.

    To use a custom class in a web application such class must be created in the App_Code folder of your website. If it's there you can call it like any other class of the framework.

    I have a post in my blog about user controls that's not specifically about what you want but will show a web control being referenced from the code behind, you can take a look at it if you want:

    http://www.gbogea.com/2008/5/17/exposing-events-in-web-user-controls/ 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 28, 2008 8:48 AM
  • User1571226316 posted

    Hello.

    I have some problems.

    I can't create get and set method, it don't recognize my controls.

    And if I use le FindControl method, i have this error

    An object reference is required for the non-static field, method, or property 'System.Web.UI.Control.FindControl(string)'

     

     

    Thursday, May 29, 2008 4:28 AM
  • User853727733 posted

    It seems you're trying to call the FindControl in a variable that has not been instantiated yet. Post the code for your control and I'll be glad to take a look.

    Thursday, May 29, 2008 8:40 AM
  • User1571226316 posted

    I don't understand all the errors when it's talking about static method or attributs.

    Here my code behind file. 

    1    using System;
    2    using System.Data;
    3    using System.Configuration;
    4    using System.Linq;
    5    using System.Web;
    6    using System.Web.Security;
    7    using System.Web.UI;
    8    using System.Web.UI.HtmlControls;
    9    using System.Web.UI.WebControls;
    10   using System.Web.UI.WebControls.WebParts;
    11   using System.Xml.Linq;
    12   using Utilities;
    13   
    14   public class CodeBehindPosition : System.Web.UI.UserControl
    15   {
    16       protected static DropDownList ddlAffaire = (DropDownList)FindControl("ddlAffair");
    17   
    18       protected void ddlAffair_SelectedIndexChanged(object sender, EventArgs e)
    19       {
    20           if (ddlAffair.SelectedValue != "Select the affair")
    21           {
    22               sQuery = "SELECT designationTower, id_Tower FROM affair a " +
    23                   "JOIN poste p on a.idaffair= p.affair_idaffair " +
    24                   "JOIN team t on p.team_idteam= t.idteam " +
    25                   "JOIN tower tow on t.tower_id_tower= tow.id_tower where idaffair = '" + ddlAffair.SelectedValue + "'";
    26               ddlTower.Items.Clear();
    27               Tool.fillDropDownList("", sQuery, "ddlTower");
    28               ddlTower.Items.Add("Select the tower");
    29               ddlTower.SelectedValue = "Select the tower";
    30               displayControls(true, true, false, false, false, false);
    31           }
    32           else
    33           {
    34               displayControls(true, false, false, false, false, false);
    35           }
    36       }
    37   
    38       ...
    39   
    40   }
    41   
    

     I just put the first function.

    On line 16 : An object reference is required for the non-static field, method, or property 'System.Web.UI.Control.FindControl(string)' 

    Thanks to spent time on it, it's nice

     

    Thursday, May 29, 2008 9:37 AM
  • User853727733 posted

    Don't worry programming is my work and my hobby! Just change you code to:

    16       protected DropDownList ddlAffaire;

    17  
    18       protected void ddlAffair_SelectedIndexChanged(object sender, EventArgs e)
    19       {

                   ddlAffaire = (DropDownList)FindControl("ddlAffair");

    20           if (ddlAffair.SelectedValue != "Select the affair")
    21           {
    22               sQuery = "SELECT designationTower, id_Tower FROM affair a " +
    23                   "JOIN poste p on a.idaffair= p.affair_idaffair " +
    24                   "JOIN team t on p.team_idteam= t.idteam " +
    25                   "JOIN tower tow on t.tower_id_tower= tow.id_tower where idaffair = '" + ddlAffair.SelectedValue + "'";
    26               ddlTower.Items.Clear();
    27               Tool.fillDropDownList("", sQuery, "ddlTower");
    28               ddlTower.Items.Add("Select the tower");
    29               ddlTower.SelectedValue = "Select the tower";
    30               displayControls(true, true, false, false, false, false);
    31           }
    32           else
    33           {
    34               displayControls(true, false, false, false, false, false);
    35           }
    36       }

    I think it should work now.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 29, 2008 9:54 AM
  • User1571226316 posted

     

    Yes, it looks good.

    Thx

    Thursday, May 29, 2008 10:17 AM
  • User853727733 posted

    No problem, happy to help. [:)]

    Thursday, May 29, 2008 10:26 AM
  • User1571226316 posted

    Last little question [:$]

    I want to call the method FindControl in my tool class. But it says that the name 'FindControl' does not exist in the current context.

    I need to add something ? Or inherit the class ?

    Thx

     

    Thursday, May 29, 2008 11:34 AM
  • User853727733 posted

    Just call the FindControl on the Page instance you have in you class.

    page.FindControl("MyControl");

    It should work, unless the control you want to find is in a FormView or DetailsView, then you have to call FindControl on the DetailsView or FormView/

    Thursday, May 29, 2008 11:42 AM
  • User1571226316 posted

    I don't have page instance. I guess i have a problem in my classe

     

     

    using System;
    using System.Data;
    using System.Configuration;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    
    namespace Utilities
    {
        public static class Tool
        {
            public static DropDownList ddl;
    
            public static System.Data.OleDb.OleDbConnection connect(String sConnectionString)
            {
                try
                {
                    sConnectionString = "Provider=msdaora;Data Source=XE;User Id=hr;Password=hr;";
    
                    System.Data.OleDb.OleDbConnection oracleConn = new System.Data.OleDb.OleDbConnection();
                    oracleConn.ConnectionString = sConnectionString;
                    oracleConn.Open();
                    return oracleConn;
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write("&lt;script>alert(\'" + e.ToString() + "\');</" + "script>");
                    return null;
                }
    
            }
    
            public static System.Data.OleDb.OleDbDataReader executeQuery(String sQuery, System.Data.OleDb.OleDbConnection oracleConn)
            {
                try
                {
                    System.Data.OleDb.OleDbCommand oleDbCmd = new System.Data.OleDb.OleDbCommand(sQuery, oracleConn);
                    System.Data.OleDb.OleDbDataReader reader = oleDbCmd.ExecuteReader();
                    return reader;
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write("&lt;script>alert(\'" + e.ToString() + "\');</" + "script>");
                    return null;
                }
            }
    
            public static int executeNoQuery(String sQuery, System.Data.OleDb.OleDbConnection oracleConn)
            {
                try
                {
                    System.Data.OleDb.OleDbCommand oleDbCmd = new System.Data.OleDb.OleDbCommand(sQuery, oracleConn);
    
                    return oleDbCmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write("&lt;script>alert(\'" + e.ToString() + "\');</" + "script>");
                    return -1;
                }
    
            }
    
            public static void deconnect(System.Data.OleDb.OleDbConnection oracleConn)
            {
                try
                {
                    oracleConn.Close();
                }
                catch (Exception e)
                {
                    HttpContext.Current.Response.Write("&lt;script>alert(\'" + e.ToString() + "\');</" + "script>");
                }
            }
    
            public static void fillDropDownList(String sConnectionString, String sQuery, String sListName)
            {
                System.Data.OleDb.OleDbConnection conn = connect(sConnectionString);
                System.Data.OleDb.OleDbDataReader reader = executeQuery(sQuery, conn);
    
                ddl = (DropDownList)page.FindControl(sListName);
                ddl.DataSource = reader;
                ddl.DataBind();
    
    
                deconnect(conn);
    
            }
        }
    }
     
    Thursday, May 29, 2008 11:48 AM
  • User1571226316 posted

    Again a little problem.. Please

    Friday, May 30, 2008 5:22 AM
  • User853727733 posted

    Are you calling your Tool class from a page's code behind, if so you can pass the Page attribute of the page as a variable. Your method would be like this:

          //comment this declaration out.

          //public static DropDownList ddl;

          public static void fillDropDownList(String sConnectionString, String sQuery, String sListName, Page page)
            {
                System.Data.OleDb.OleDbConnection conn = connect(sConnectionString);
                System.Data.OleDb.OleDbDataReader reader = executeQuery(sQuery, conn);


                DropDownList ddl = (DropDownList)page.FindControl(sListName);
                ddl.DataSource = reader;
                ddl.DataBind();


                deconnect(conn);

            }

    And from a code behind file you would call it like this:

    Tool.fillDropDownList(myConnectionString, myQuery, myListName, this.Page);

    Also, if you don't have a good reason to declare the DropDownList outsite the scope of the method move the declaration to the method. If you need it for something specific then just leave it alone.

    Let me know how it works.

    Friday, May 30, 2008 8:44 AM
  • User1571226316 posted

    It works ! Well, not completly, but I can build the solution.
    Now, I can't find the control. I have a null pointer exception.

    But I think know why. My control is on an usercontrol.

    How can I find it ? I need to declare the usercontrol ? I tried, but never successfully.

    Friday, May 30, 2008 9:22 AM
  • User853727733 posted

    You can change the paramter of the method to receive a Control instead of Page, so you can pass a page instance or a user control.

          public static void fillDropDownList(String sConnectionString, String sQuery, String sListName, Control control)
            {
                System.Data.OleDb.OleDbConnection conn = connect(sConnectionString);
                System.Data.OleDb.OleDbDataReader reader = executeQuery(sQuery, conn);


                DropDownList ddl = (DropDownList)control.FindControl(sListName);
                ddl.DataSource = reader;
                ddl.DataBind();


                deconnect(conn);

            }

    Using it like this you can pass a page or a control:

    fillDropDownList(myConnectionString, myQuery, myListName, this.Page)

    or

    fillDropDownList(myConnectionString, myQuery, myListName, myUserControl)

    I think it will work.


     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 30, 2008 4:28 PM
  • User1571226316 posted

    It works very good.

    Thx a lot 

    Saturday, May 31, 2008 6:58 AM