Reputation: 762
I got a comboBox
in FORM1 that gets the value from the database
FORM1 Code:
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.
FORM2 Code:
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. It only updates after I run the program again.
Upvotes: 0
Views: 226
Reputation: 47968
With this code:
Form1 nf = new Form1();
nf.fillComboBox();
You are creating a new Form1
after db update (and not showing it). You are not refreshing the original Form1
.
To see this, add: nf.Show();
after the fillComboBox() call.
You have to refresh the original Form1
after closing Form2
.
example:
if(form2.ShowDialog() == DialogResult.OK)
fillComboBox();
and in fillComboBox
, you should clear comboBox3.Items
before adding new entries.
Upvotes: 4