簡體   English   中英

使用 asp.net 遍歷文本框

[英]Iterating through textboxes using asp.net

我正在用 asp.net 建立一個頁面。 我有一個包含文本框和提交按鈕的表格的表格。 提交表單時,我想獲取輸入到 TextBoxes 中的所有文本並對其進行操作。 為此,我有以下方法:

protected void Button1_Click(object sender, EventArgs e)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    foreach (Control c in this.Controls)
    {
        if (c.GetType().Name == "TextBox")
        {
            TextBox tb = (TextBox)c;
            sb.AppendLine(tb.Text);
        }
    }
    Label1.Text = sb.ToString();
}

問題在於控件顯然不包含我的任何文本框。 當我遍歷控件並打印出它們的名稱時,我得到的唯一一個是“site_master”。 (我也嘗試過 Controls 和 Page.Controls 而不是 this.Controls)。

我的迭代器有問題嗎? 是否有另一種方法可以遍歷表格或頁面中的所有文本框? 實現這一目標的最佳方法是什么?

考慮到您知道所有文本框控件,構建List<Textbox>會不會太過分?

List<Textbox> txtBoxes = new List<Textbox>();
txtBoxes.Add(tb1);
txtBoxes.Add(tb2);
//etc..

然后你有一個很好的清單可以使用

如果我知道控件都在給定的包含控件中,我將簡單地輪詢該控件控件。 例如, this.Form.Controls 但是,如果它們可以嵌套在其他子控件中,那么您可以遞歸地探索來自公共外部容器的深度。

private IEnumerable<T> FindControls<T>(Control parent) where T : Control
{
    foreach (Control control in parent.Controls)
    {
        if (control is T)
            yield return (T)control;

        foreach (T item in FindControls<T>(control))
            yield return item;
    }
}

因此,這將允許您檢索所有TextBox子項。

List<TextBox> textBoxes = this.FindControls<TextBox>(this).ToList();
string output = string.Join(",", textBoxes.Select(tb => tb.Text));

我將假設您使用的是 web forms ASP.NET。 通常,您在 aspx 頁面上使用類似於

<asp:TextBox ID="someId" runat="server/>

如果你已經這樣做了,那么在你后面的代碼中你應該能夠引用變量someId和屬性Text來獲取/設置控件中的文本。

如果您在服務器上動態構建控件,您應該能夠將它們粘貼在列表中並遍歷它。 確保在頁面生命周期的正確部分創建控件並將它們添加到表中。 當您將它們添加到表中的單元格時,您還可以在列表中保留對控件的引用,並在事件處理程序中枚舉該列表。

也許類似於(我沒有編譯它,所以可能存在問題):

public class MyPage: Page
{
  private List<TextBox> TxtBoxes = new List<TextBox>();

  //registered for the preinit on the page....
  public void PreInitHandler(object sender, EventArgs e)
  {
      for(var i = 0; i < 2; i++)
      {
        var txtBox = new TextBox{Id = textBox+i};
        //...add cell to table and add txtBox Control
        TxtBoxes.Add(txtBox);
      }
  }
}

暫無
暫無

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

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