【问题标题】:how do I check whether a text box that is dynamically created is populated with data?如何检查动态创建的文本框是否填充了数据?
【发布时间】:2016-02-19 21:02:49
【问题描述】:

我有 10 行文本框(4 列)

如果所有 10 行都填充了数据,我需要触发一个事件来做某些事情。

我是 Web 开发的新手,我不太了解如何引用 HTML 页面上由代码隐藏动态生成的项目。这是它在 HTML 中的样子:

<tr align="center">
 <td style="height: 85px">
    </td>
     <td align="center" style="width: 440px; height: 310px">
       <fieldset class="field1" style="text-align: center">
          <legend class="Eblegend" id="legendObligation2">
              <%=frameName%>
             </legend>
            <asp:Panel ID="pnlTable" runat="server" Width="620px" Height="310px">
            </asp:Panel>
           </fieldset>
    </td>
</tr>

此代码变成一个可编辑的表格(4 列和 10 行)。

我需要检查是否所有框都已填满,以便启用“下一步”按钮。

问题是,我不知道如何在动态生成的表格上引用这些“单元格”,以便我可以说“如果不是 null 或空,请执行此操作”

谁能帮帮我?

【问题讨论】:

  • 如果你使用的是 asp:TextBox foreach(var tbCtrl in this.Controls.OfType&lt;TextBox&gt;()) { },你能做这样的事情吗?

标签: c# asp.net


【解决方案1】:

为了能够访问这些值,您还需要在 PostBack 的情况下创建 TextBoxes。这必须很早就发生,并且控件的 ID 必须相同。

以下代码显示了一个动态创建 TextBox 并稍后读取值的小示例:

ASPX:

<form id="form1" runat="server">
    <div>
        <asp:Button ID="btnCreateTextBox" runat="server" Text="Create TextBox" OnClick="btnCreateTextBox_Click" />
    </div>
    <div>
        <asp:PlaceHolder ID="placeHolder" runat="server"></asp:PlaceHolder>
    </div>
    <div>
        <asp:Button ID="btnPostBack" runat="server" Text="Do a postback" />
    </div>
    <div>
        <asp:Label ID="lbl" runat="server" />
    </div>
</form>

代码隐藏:

public partial class WebForm1 : System.Web.UI.Page
{
    protected TextBox txt;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (Request.Form.AllKeys.Any(x => x == "TextBox1"))
            CreateTextBox();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (txt != null)
            lbl.Text = "TextBox value is " + txt.Text;
        else
            lbl.Text = "No value in TextBox";
    }

    protected void btnCreateTextBox_Click(object sender, EventArgs e)
    {
        if (txt == null)
        {
            CreateTextBox();
        }
    }

    private void CreateTextBox()
    {
        txt = new TextBox();
        txt.ID = "TextBox1";
        placeHolder.Controls.Add(txt);
    }
}

重要的部分是如果 PostBack 数据中有值,则在 OnInit 中创建具有相同 ID 的 TextBox。即使 TextBox 为空,AllKeys 集合中也存在 TextBox 的键(示例中为 TextBox1)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多