I have created an application which inserts data into a SQL database. Basically, from the main form, users open a second form which prompts them for the data which will go into the database. The code looks like this:
private void submitButton_Click(object sender, EventArgs e)
{
//Get form values
try
{
//Open test connection
}
catch (Exception ex)
{
//Handle errors
}
finally
{
//Close test connection
}
//Run the SQL statements
try
{
//Inser SQL data
}
catch (Exception ie)
{
//Handle errors
}
finally
{
//Close the connection
if (conn.State != ConnectionState.Closed)
{
//Close the connection
}
//Close the window
this.Close();
//Tell the main form to reload SQL data (not working)
mainForm firstForm;
firstForm = new mainForm();
firstForm.refreshCall();
}
}
}
So basically, when the user hits OK (submitButton), the data is inserted, the window is closed, and the refreshCall() method is called. My method ‘refreshCall’ is supposed to refresh the SQL data which is outputted on the main form, like this:
public void refreshCall()
{
SqlConnection conn = new SqlConnection("Data Source=SERVER\\SQL_DB;Initial Catalog=dataTable;Integrated Security=True");
try
{
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT part_num from dbo.Parts", conn);
adapter.Fill(ds);
this.listParts.DataSource = ds.Tables[0];
this.listParts.DisplayMember = "part_num";
conn.Close();
}
catch (SqlException odbcEx)
{
MessageBox.Show("There was an error connecting to the data source.\nError Code: 1001", "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
However, when this method is called, the data remains un-refreshed, which means I have to close the application and reload it to see my changes. Is there something I’m doing wrong in my code that causes the SQL data to remain unchanged? Is there a better way to do this? I should also note that I use the exact same code from refreshCall to load the data when the form is initialized, and it works fine.
Any help is appreciated!
It appears that the second form is creating a new instance of the main form. The new instance never gets displayed. You need to get your existing main form for your refreshCall.