I have this form with a button and َPanel. When I press the button I want to add a Row to dataGridView1
User control code:
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 code:
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)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
UserControl1 user = new UserControl1();
user.setRow();
}
Should be
private void button1_Click(object sender, EventArgs e)
{
UserControl1.Instance.setRow();
}
and constructor of UserControl1 should look like
public UserControl1()
{
_instance = this;
InitializeComponent();
}
In your code you are creating 3 instances of your UserControl and it seems like you want to only have one. When you call a method on one of those instances it doesnt in no way influence the other instances.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.