簡體   English   中英

選定選項卡中所有文本框的清除文本

[英]Clear Text of All Textboxes in Selected Tab

我有一個具有tab control的表單,每個選項卡都有許多textboxeslabelsbuttons 我想讓用戶清除所選標簽的文本框中的所有文本。

我試過了

    private void resetCurrentPageToolStripMenuItem_Click(object sender, EventArgs e)
    {
        foreach (TextBox t in tabControl1.SelectedTab.Controls)
        {
            t.Text = "";
        }
    }

上面的代碼拋出InvalidCastException並使用Message Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox InvalidCastException Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox

請問我做錯了什么,我該怎么糾正呢?

在foreach循環中使用OfType<T>()

private void resetCurrentPageToolStripMenuItem_Click(object sender, EventArgs e)
{
    foreach (TextBox t in tabControl1.SelectedTab.Controls.OfType<TextBox>())
    {
        t.Text = "";
    }
}

替代方案:

foreach (Control control in tabControl1.SelectedTab.Controls) 
{
    TextBox text = control as TextBox;
    if (text != null) 
    {
        text.Text = "";
    }
}

在網上找到它並且它有效

    void ClearTextBoxes(Control parent)
    {
        foreach (Control child in parent.Controls)
        {
            TextBox textBox = child as TextBox;
            if (textBox == null)
                ClearTextBoxes(child);
            else
                textBox.Text = string.Empty;
        }
    }

    private void resetCurrentPageToolStripMenuItem_Click(object sender, EventArgs e)
    {
        ClearTextBoxes(tabControl1.SelectedTab);
    }

使用可以簡單地遍歷所選選項卡中的所有控件,並在清除文本之前檢查control type是否為TextBox並清除文本。

 foreach (Control item in tabControl1.SelectedTab.Controls)
            {
                if (item.GetType().Equals(typeof(TextBox)))
                {
                    item.Text = string.Empty;
                }
            }

如果您的tabcontrol中嵌套了文本框。 你需要在這里寫一個遞歸方法,因為ofType方法不會返回你的嵌套文本框。

 private void ResetTextBoxes(Control cntrl)
 {
     foreach(Control c in cntrl.Controls)
     {
          ResetTextBoxes(c);
          if(c is TextBox)
            (c as TextBox).Text = string.Empty;
     }
 }

或者,如果您只在TabControl的基礎級別上有文本框,則可以使用它

foreach(var tb in tabControl1.OfType<TextBox>())
 {
    tb.Text = string.Emtpy;
}
 var textBoxNames = this.tabControl1.SelectedTab.Controls.OfType<TextBox>();
            foreach (var item in textBoxNames)
            {
                var textBoxes = tabControl1.SelectedTab.Controls.Find(item.Name, true);
                foreach (TextBox textBox in textBoxes)
                {
                    textBox.Clear();
                }
            }

暫無
暫無

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

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