我有一个带有按钮和面板的表格。当我按下按钮时,我想在dataGridView1
用户控制代码:
public partial class UserControl1 : UserControl
{
private static UserControl1 _instance;
public static UserControl1 Instance
{
get
{
if (_instance == null)
_instance = new UserControl1();
return _instance;
}
}
public UserControl1()
{
InitializeComponent();
}
public void setRow()
{
String[] row = { "TEST", "TEST", "TEST", "TEST" };
dataGridView1.Rows.Add(row);
}
}
Form1代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.Controls.Add(new UserControl1());
UserControl1.Instance.Dock = DockStyle.Fill;
UserControl1.Instance.BringToFront();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
UserControl1 user = new UserControl1();
user.setRow();
}
private void button2_Click(object sender, EventArgs e)
{
}
}
答案 0 :(得分:0)
private void button1_Click(object sender, EventArgs e)
{
UserControl1 user = new UserControl1();
user.setRow();
}
应该是
private void button1_Click(object sender, EventArgs e)
{
UserControl1.Instance.setRow();
}
和UserControl1的构造函数应该看起来像
public UserControl1()
{
_instance = this;
InitializeComponent();
}
在您的代码中,您正在创建3个UserControl实例,而您似乎只想拥有一个实例。当你在其中一个实例上调用方法时,它不会影响其他实例。