如何在usercontrols中找到控件并将其传递给字符串构建器 [英] how to find controls in usercontrols and pass it to string builder
本文介绍了如何在usercontrols中找到控件并将其传递给字符串构建器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以通过这两个代码遍历面板上的控件
Form4 fl = new Form4();
StringBuilder sb = new StringBuilder();
foreach(控制c在panel1.Controls中)
{
if(c是ComboBox)
{
ComboBox cb =(ComboBox)c;
sb.Append(cb.Text);
fl.comboBox1.Text = sb.ToString();
fl.Show();
}
}
或者通过这个
List< combobox> lst = new List< combobox>();
void GetComboBoxValues()
{
StringBuilder sb = new StringBuilder();
foreach(lst中的ComboBox c)
{
sb.Append(c.Text +\\\\ n);
}
MessageBox.Show(sb.ToString());
}
但我在面板上添加了一个usercontrol,其中包含一个组合框和文本框,如何找到控件并添加到字符串构建器
解决方案
您需要将用户控件中的那些控件(ComboBox,TextBox等)公开为公共属性,以便您可以像访问其他属性一样访问这些控件。 UserControl。
例如:
class MyUserControl:UserControl
{
public TextBox MyTextBox
{
get {return textBox1;}
}
public ComboBox MyComboBox
{
get { return comboBox1;}
}
}
//表格类
foreach(在panel1.Controls中控制ctrl)
{
if( ctrl是MyUserControl)
{
MyUserControl myCtrl = ctrl as MyUserControl;
//myCtrl.TextBox.Text
//myCtrl.ComboBox.Text // ????希望你明白这个,
}
}
< pre> ;
i can iterate through the controls which are on panel by this two code
Form4 fl = new Form4(); StringBuilder sb = new StringBuilder(); foreach (Control c in panel1.Controls) { if (c is ComboBox) { ComboBox cb = (ComboBox)c; sb.Append(cb.Text); fl.comboBox1.Text = sb.ToString(); fl.Show(); } } OR by this List<combobox> lst = new List<combobox>(); void GetComboBoxValues() { StringBuilder sb = new StringBuilder(); foreach (ComboBox c in lst) { sb.Append(c.Text + "\r\n"); } MessageBox.Show(sb.ToString()); }
but i add a panel and on panel a usercontrol which contains a combobox and textbox how that can be possible to find controls and add to the string builder
解决方案
You need to expose those Controls ( ComboBox,TextBox etc) inside your user control as Public properties so that you can access these control just like the other properties of the UserControl.
eg:
class MyUserControl :UserControl { public TextBox MyTextBox { get {return textBox1;} } public ComboBox MyComboBox { get { return comboBox1;} } } //Form Class foreach(Control ctrl in panel1.Controls) { if(ctrl is MyUserControl) { MyUserControl myCtrl = ctrl as MyUserControl; //myCtrl.TextBox.Text //myCtrl.ComboBox.Text //????Hope you get this, } } <pre>
这篇关于如何在usercontrols中找到控件并将其传递给字符串构建器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文