c面板可视性中的文本框

本文关键字:文本 可视性 | 更新日期: 2023-09-27 18:15:32

我正试图在面板内显示一个5x5的文本框网格。单击Show后,空文本框将为空(visible: false;(,非空文本框会显示在其适当位置。

我当前的.aspx文件:

<body>
  <form id="form1" runat="server">
    <div>
      <asp:Panel ID="Panel1" runat="server">
      </asp:Panel>
    </div>
    <asp:Button ID="btnShow" runat="server" Text="Show" onclick="btnShow_Click" />
  </form>
</body>

代码背后:

protected void Page_Load(object sender, EventArgs e)
{
    //Declare the array 
    //int[,] wsArray = new int[5, 5];
    //char[] delimiterChars = { ' ', ' ', ' ' };
    StringWriter stringWriter = new StringWriter();
    // Put HtmlTextWriter in using block because it needs to call Dispose.
    using (HtmlTextWriter hw = new HtmlTextWriter(stringWriter))
    {
        int number = 1;
        //hw.Write("<table>");
        for (int i = 0; i <= 4; i++)
        {
            //hw.Write("<tr>");
            for (int j = 0; j <= 4; j++)
            {
                System.Random rnd = new Random();
                TextBox tb = new TextBox();
                tb.ID = number.ToString();
                tb.MaxLength = 1;
                tb.Width = Unit.Pixel(40);
                tb.Height = Unit.Pixel(40);
                Panel1.Controls.Add(tb);
                number++;                    
            }
            Literal lc = new Literal();
            lc.Text = "<br />";
            Panel1.Controls.Add(lc);
        }
    }
}
protected void btnShow_Click(object sender, EventArgs e)
{
    foreach (Control text in Panel1.Controls)
    {
        if (text == null)
        {
            text.Visible = false;
        }
        else
        {
            text.Visible = true;
        }
    }
}

c面板可视性中的文本框

您需要先获取文本框然后检查其Text属性。在按钮处理程序btnShow_Click():中尝试此操作

foreach (Control control in Panel1.Controls)
{
    var textBox = control as TextBox;
    if (textBox != null)
    {
        textBox.Visible = !string.IsNullOrEmpty(textBox.Text);
    }
}

顺便说一句,如果你从服务器端设置Visible=False,你的网站布局可能(可能不会(中断,因为控件根本不会被渲染。在这种情况下,此行:textBox.Visible = !string.IsNullOrEmpty(textBox.Text);替换为以下内容:

if (string.IsNullOrEmpty(textBox.Text))
{
    textBox.Style["visibility"] = "hidden";
}