问题描述
我的 WinForms C# 应用程序中有以下代码:
private void button2_Click(object sender,EventArgs e)
{
var txtBox2 = new System.Windows.Forms.RichTextBox();
TabPage createdtabpage = new TabPage("I am a tab");
tabControl1.TabPages.Add(createdtabpage);
createdtabpage.Controls.Add(txtBox2);
}
我想在单击单独的按钮时访问 txtBox2
的文本。我有这个代码:
private void button1_Click(object sender,EventArgs e)
{
//Either this:
string text = txtBox2.Text;
//or maybe this:
string text = createdtabpage.Controls[txtBox2]
}
但是,此代码不起作用,因为外部函数无法访问这些变量。
有没有人有从外部函数访问这些 TabPage 控件的好方法?
感谢您的帮助
解决方法
从控件选项卡中,选择选项卡,然后按名称找到所需的控件。
使用此代码
private void button1_Click(object sender,EventArgs e)
{
var textBox = (RichTextBox)tabControl1.SelectedTab.Controls["txtbox2"];
MessageBox.Show(textbox.Text);
}
如果没有名称,您必须浏览所有控件,例如,如果您有多个 RichTextBox 控件,请知道它们的位置顺序。
foreach (Control control in tabControl1.SelectedTab.Controls)
{
if(control is RichTextBox)
{
MessageBox.Show(control.Text);
}
}