簡體   English   中英

從后面的代碼內部的類訪問TextBox和DropDownList值

[英]access TextBox And DropDownList Values from a class inside code behind

我知道我對類與繼承之間的關系缺乏基本的了解

我發現很難理解一個簡單的東西:

可以從后面的代碼訪問給定的DDlTextBox

int selected = DDLID.SelectedIndex ;

string userInput = TBXID.Text;

現在從放置在代碼后面的類中:

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

我試圖“整理”我的代碼,以便能夠在其他一些項目中重用它

...所以我已將與該類中的代碼相關的所有全局變量移至該類中,而我不能做的就是使用webControls Values分配變量

怎么做呢?

更新

我能想到的一種方法是通過參數

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;
   }
} 

像這樣創建一個不同的類

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;
    }
}

您可以從下面的代碼中創建一個實例,如下所示

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

現在您可以訪問DropDown索引和文本為

cv.DropDownIndex;  
cv.TextBoxValue;

盡管我為此提供了答案,但請注意:

  • 記住Web應用程序的無狀態本質以及您將如何使用它。
  • 在ASP.NET中,創建類的實例來保存服務器控件的值將是低效的,因為可以從后面的代碼直接訪問這些控件及其值。 使用這種方法將產生額外的開銷。
  • 如果您認真學習可重用性,我強烈建議您學習面向對象編程的基礎知識。 一旦掌握了OOP,您就會清楚地知道何時應用OOP原則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM