簡體   English   中英

無法從動態創建的文本框中讀取值

[英]Cannot read value from dynamically created textbox

我想在按鈕單擊事件中檢索文本框值,但是一旦單擊按鈕,就會觸發回發並且該值為空。 我試圖在( !isPostBack )中創建文本框,但這似乎不起作用。

protected void Page_Load(object sender, EventArgs e)
{
     Form.Controls.Add(t);
}

protected void Page_PreInit(object sender, EventArgs e)
{
     predictionList = dc.getPredictions(Convert.ToInt32(Session["accountId"]));
     fixtureList = dc.getFixtures();
     t.CssClass = "panel panel-success table table-striped";
     sortLists();
     foreach (Fixture f in newList)
     {
          TableRow tr = new TableRow();
          TableCell tc1= new TableCell();
          TextBox tb1= new TextBox();
          tb1.ID = "tb1";
          tc1.Controls.Add(tb1);
          tr.Cells.Add(tc1);
          t.Rows.Add(tr);
     }
}

在這里添加控件,在這里我要處理文本框中的內容:

protected void btSubmit_Click(object sender, EventArgs e)
{
     foreach (TableRow r in t.Rows)
     {
         string textboxRead= ((TextBox)r.FindControl("tb1")).text;
         int textboxInt = Convert.ToInt32(textboxRead);
     }
}

難道是因為FindControl()不能遞歸地工作,所以找不到文本框?

即您已經將TextBox添加到TableCell ,但是您正在TableRow而不是TableCell上執行FindControl()調用。 因此,可以從Cell調用FindControl()或使用遞歸版本。

有關FindControl()的遞歸版本,請參見: 在ASP.NET中查找控件的更好方法

嘗試這個:

TextBox tb1;

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        tb1 = ((TextBox)r.FindControl("tb1"));                
    }
}

protected void btSubmit_Click(object sender, EventArgs e)
{
     string textboxRead = tb1.Text; // here you can get the tb1.Text
     int textboxInt = Convert.ToInt32(textboxRead);
}

希望這會幫助你。

protected void AddTextBox(object sender, EventArgs e)
{
    int index = pnlTextBoxes.Controls.OfType<TextBox>().ToList().Count + 1;
    this.CreateTextBox("txtDynamic" + index);
}


private void CreateTextBox(string id)
{
    TextBox txt = new TextBox();
    txt.ID = id;
    pnlTextBoxes.Controls.Add(txt);

    Literal lt = new Literal();
    lt.Text = "<br />";
    pnlTextBoxes.Controls.Add(lt);
}

有關詳細信息,請參見此鏈接: http : //www.aspsnippets.com/Articles/Get-Value-Text-of-dynamically-created-TextBox-in-ASPNet-using-C-and-VBNet.aspx

您需要為所有動態創建的控件提供ID。 這是強制性的,以防止在回發時產生任何歧義。

其中包括trtc1tb1甚至可能還有t控件。

另外,要查找值,請使用以下代碼段:

protected void btSubmit_Click(object sender, EventArgs e)
{
    foreach (TableRow tr in t.Rows)
    {
        var tc1 = (TableCell)tr.FindControl("tc1");
        var tb1 = (TextBox)tc1.FindControl("tb1");
        int textboxInt = Convert.ToInt32(tb1.Text);
     }
}

暫無
暫無

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

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