0

パネル内にテキスト ボックスの 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;
        }
    }
}
4

1 に答える 1

1

最初にテキストボックスを取得する必要があります。次に、そのプロパティを確認し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";
}
于 2013-05-28T01:39:44.797 に答える