LoneXcoder
LoneXcoder

Reputation: 2163

access TextBox And DropDownList Values from a class inside code behind

i know i lack a base knowlage of the realtions between classes and inheritance

i find it hard to understand a simple thing :

a given DDl or TextBox could be accessed from code behind

int selected = DDLID.SelectedIndex ;

string userInput = TBXID.Text;

Now from a class that is placed in code behind :

public static class ControlsValue
{
   public static int UserSel = DDLID.Selected.index;
   public static string UserText = TBXID.Text;
} 

i was trying to "Arange" my code so i will be able to reuse it in some other projects

...so i have moved all global variables related to the code in that class into the class and what i can't do is assign variables with webControls Values

what is the way to do it ?

update

a way i could think of is via parameter

public static class ControlsValue
{
   public static void getValues(DropDownList DDLID)
   {
        public static int UserSel = DDLID.Selected.index;
   }
   public static string UserText(TextBox TBXID)
   {
      return TBXID.Text;
   }
} 

Upvotes: 1

Views: 1376

Answers (1)

Tariqulazam
Tariqulazam

Reputation: 4585

Create a different class like this

public class ControlValues{

    private int_dropDownIndex;
    public int DropDownIndex{
         get { return _dropDownIndex; }
         set { _dropDownIndex= value; }
    }

    private string _textBoxValue;
    public string TextBoxValue{
         get { return _textBoxValue; }
         set { _textBoxValue= value; }
    }

    public ControlValues(int dropDownIndex, string textBoxValue){
         this._dropDownIndex = dropDownIndex;
         this._textBoxValue = textBoxValue;
    }
}

You can create an instance from your code behind like below

ControlValues cv= new ControlValues(DDLID.Selected.index, TBXID.Text);

Now you can access the DropDown index and text as

cv.DropDownIndex;  
cv.TextBoxValue;

Although I provided an answer for this, Please note:

  • Remember the stateless nature of web application and the way you are going to use this.
  • In ASP.NET, it will be inefficient to create an Instance of class to hold values of server control because those controls and their values are directly accessible from the code behind. Using this approach will be an extra overhead.
  • If you are serious about learning re-usability, I would strongly recommend you to learn basics of object oriented programming. Once you have a good grip of OOP, you will see clearly when to apply OOP principles.

Upvotes: 1

Related Questions