Clear Text of All Textboxes in Selected Tab

2020-03-18 07:21发布

问题:

I have a form that has a tab control and each tab has a number of textboxes,labels and buttons. I want to enable the user to clear all text in the textboxes of the selected tab.

I have tried

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

The above code throw an InvalidCastException with the Message Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox.

Pls what did i do wrong and how can i correct it?

回答1:

Use the OfType<T>() in the foreach loop.

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

Alternative:

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


回答2:

Found this online and it worked

    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);
    }


回答3:

Use can simply iterate through all the controls in the selected tab and before clearing the text check if the control type is TextBox and clear the text.

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


回答4:

if you have textboxes nested in your tabcontrol. you need to write a recursive method here as ofType method will not return your nested textboxes..

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

Alternatively if you have got textboxes only on the base level of TabControl you can use this

foreach(var tb in tabControl1.OfType<TextBox>())
 {
    tb.Text = string.Emtpy;
}


回答5:

 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();
                }
            }