我comboBox
在 FORM1 中有一个从数据库中获取值的
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);
}
}
}
}
从 FORM1 我有一个button
打开 FORM2 的地方,我可以在数据库中添加数据。
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
}
我检查了数据库并验证了数据是否已添加。
问题是当我在数据库中添加数据时,组合框不会更新它加载的数据。只有在我再次运行程序后才会更新。