ComboBox不更新

时间:2013-07-18 04:39:16

标签: c# winforms combobox

我在FORM1中得到一个comboBox,它从数据库中获取值

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
}

我检查数据库并验证数据是否已添加 问题是当我在数据库中添加数据时,comboBox不会更新它加载的数据。它只会在我再次运行程序后更新。

1 个答案:

答案 0 :(得分:4)

使用此代码:

Form1 nf = new Form1();
nf.fillComboBox();

您在db更新后创建了一个新的Form1(并且没有显示它)。您没有刷新原始Form1

要查看此内容,请在fillComboBox()调用后添加:nf.Show();

关闭Form1后,您必须刷新原始Form2

示例:

if(form2.ShowDialog() == DialogResult.OK)
    fillComboBox();

并且在fillComboBox中,您应该在添加新条目之前清除comboBox3.Items