Reputation: 4963
I have a winform say winForm1 which has combobox. i am binding this combobox on Form_Load event like this
SqlCommand cmd = new SqlCommand("SELECT DISTINCT(TXT_TARGET_NUMBER) FROM TBL_CDR_ANALYZER", sqlCon);
cboTargetNo.Properties.Items.Clear();
cboTargetNo.Properties.Items.Add("Choose Target Number");
sqlCon.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cboTargetNo.Properties.Items.Add(dr["TXT_TARGET_NUMBER"]);
}
sqlCon.Close();
cboTargetNo.SelectedIndex = 0;
Now this form also contains a button say btn1. on Click event of this button i am opening a new winform say winForm2 using ShowDialog() function.
On WinForm2 i have a button btn2 which insert some values in sql. i want after values insert in sql, Combobox on winForm1 should Refresh. How can i do this. i am clueless where to start for this.
Upvotes: 0
Views: 3282
Reputation: 63065
If you want to update each form1
from form2
better option is having event handler.
Form2 Code
public event EventHandler myEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// update data here
// inform form 2 about data added
if (myEvent != null)
{
myEvent(this,e);
}
}
Form1 Code
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.myEvent += new EventHandler(f2_myEvent);
f2.ShowDialog();
}
void f2_myEvent(object sender, EventArgs e)
{
//Refresh your ddl
}
Upvotes: 2
Reputation: 10054
If you want immediate update, you could create a delegate to refresh the Combo from your dialog after hitting the button.
Create a delegate in your main form:
public delegate void ComboDelegate();//namespace level
public void RefreshCombo(string itemToAdd){
//do your add item here
}
then in your Dialog Form class:
public ComboDelegate cd;
Create your Dialog Form with the cd set to RefreshCombo:
winForm2 = new Winform(){ cd = RefreshCombo );
then at your button Click simply call:
cd(itemToUpdate);
Upvotes: 1
Reputation: 223277
Simplist way would be to to extract the code for ComboBox update to a method, Call it from Form_Load event
, Later since you are using Form.ShowDialog
, you can call the method again to get the latest record from the database and bind the CombobBox again. Something like:
WinForm2 frm2 = new WinForm2();
frm2.ShowDialog();
RefreshCombo();
Where RefreshCombo
is a method :
private void RefreshCombo()
{
SqlCommand cmd = new SqlCommand("SELECT DISTINCT(TXT_TARGET_NUMBER) FROM TBL_CDR_ANALYZER", sqlCon);
cboTargetNo.Properties.Items.Clear();
cboTargetNo.Properties.Items.Add("Choose Target Number");
sqlCon.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cboTargetNo.Properties.Items.Add(dr["TXT_TARGET_NUMBER"]);
}
sqlCon.Close();
cboTargetNo.SelectedIndex = 0;
}
Upvotes: 1