假设我有一个名为FlowLayoutPanel的panel1,其中包含control1、control2、control3。每个控件都有一个方法.doSomething()或存储的变量.name。我怎样才能访问这些?
类似于:
panel1.Controls[0].doSomething();
string name = panel1.Controls[0].name;我的代码:
public partial class ChatItem : UserControl
{
public string username, description, mainUser; /// <summary>
/// mainUser este utilizatorul care foloseste in prezent aplicatia
/// </summary>
MySqlConnection basicConnection, chatUpdater, msgSender;
#region Properties
[Category("Custom Properties")]
public string user
{
get { return label1.Text; }
set { label1.Text = username = value; }
}
[Category("Custom Properties")]
public Image profilePicture
{
get { return pictureBox1.Image; }
set { pictureBox1.Image = value; }
}
public Image dot
{
get { return pictureBox2.Image; }
set { pictureBox2.Image = value; }
}
#endregion
public void doSomething()
{
MessageBox.Show("something");
}
}我想访问.doSomething()和description.How,我能这样做吗?
发布于 2020-03-12 10:00:25
您应该在控件属性上迭代,但是控件应该转换为您的类型,以使用特定于您的类的字段/方法。
foreach(var control in panel1.Controls)
{
if (control is ChatItem chatItem) // to ensure the casting can be done
{
string description= chatItem.description;
chatItem.doSomething();
}
}https://stackoverflow.com/questions/60650441
复制相似问题