[英]ComboBox don't update
I got a comboBox
in FORM1 that gets the value from the database 我在FORM1中有一个comboBox
,它从数据库中获取值
FORM1 Code: FORM1代码:
public void fillComboBox()
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select LastName, FirstName, MiddleName from EMP", myDatabaseConnection))
using (SqlDataReader sqlreader = mySqlCommand.ExecuteReader())
{
while (sqlreader.Read())
{
string Lname = sqlreader.GetString(sqlreader.GetOrdinal("LastName"));
string Fname = sqlreader.GetString(sqlreader.GetOrdinal("FirstName"));
string Mname = sqlreader.GetString(sqlreader.GetOrdinal("MiddleName"));
string fullName = Lname + ", " + Fname + " " + Mname;
comboBox3.Items.Add(fullName);
}
}
}
}
From the FORM1 I have a button
that opens the FORM2 where I could add data in the database. 从FORM1,我有一个打开FORM2的button
,可以在其中添加数据库中的数据。
FORM2 Code: FORM2代码:
public void addData()
{
string a = "INSERT INTO Emp(LastName, FirstName, MiddleName) Values('"+textBox1.Text+"', '"+textBox2.Text+"', '"+textBox3.Text+"')";
using (SqlConnection myDatabaseConnection1 = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection1.Open();
using (SqlCommand mySqlCommand = new SqlCommand(" " + a + " ", myDatabaseConnection1))
mySqlCommand.ExecuteReader();
}
}
private void button1_Click(object sender, EventArgs e)
{
addData();
Form1 nf = new Form1();
nf.fillComboBox();
this.close
}
I check the database and verified the data is added. 我检查数据库并验证是否添加了数据。
The problem is when I add data in the datatabase the comboBox don't update the data it loads. 问题是,当我在数据库中添加数据时,comboBox不会更新其加载的数据。 It only updates after I run the program again. 只有在我再次运行该程序后,它才会更新。
With this code: 使用此代码:
Form1 nf = new Form1();
nf.fillComboBox();
You are creating a new Form1
after db update (and not showing it). 您将在数据库更新后创建一个新的Form1
(并且不显示它)。 You are not refreshing the original Form1
. 您没有刷新原始Form1
。
To see this, add: nf.Show();
要查看此内容,请添加: nf.Show();
after the fillComboBox() call. 在fillComboBox()调用之后。
You have to refresh the original Form1
after closing Form2
. 关闭Form2
之后,必须刷新原始Form1
。
example: 例:
if(form2.ShowDialog() == DialogResult.OK)
fillComboBox();
and in fillComboBox
, you should clear comboBox3.Items
before adding new entries. 在fillComboBox
,应在添加新条目之前清除comboBox3.Items
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.