Form Refreshing Problem in c# - c#

I have two form form A and from B . When user click button on form A , Form B will apperar but Form A is already open .User can set data in form B. When user click add Button in Form B ,the data will pass to form A and textbox in form A will
set data with pass data. I received passed data but Form A's textbox not fill with data.How could I do that ?
In Form B add button clik
private void btnAdd_Click(object sender, EventArgs e)
{
EmployeeAddressEntity empAdd = new EmployeeAddressEntity();
empAdd = AddEmployee();
this.Close();
NewEmployee emp = new NewEmployee();
emp.FillAddressGrid(empAdd);
}
In Form A
public void FillAddressGrid(EmployeeAddressEntity emp)
{
txtAddressName.Text = emp.name;
dgvAddress.Rows.Add(emp.type,emp.name,emp.homephone,emp.fax,emp.email,emp.address,emp.country_id);
//int a = dgvAddress.Rows.Count;
dgvAddress.EndEdit();
dgvAddress.Refresh();
dgvAddress.Parent.Refresh();
this.Refresh();
}

In FormB, define a private field that stores the reference to FormA, and create a custom constructor to pass the reference.
public FormB(FormA form) {
this.m_FormA = form;
}
private FormA m_FormA;
When you show FormB from FormA, pass the reference.
using (FormB form = new FormB(this)) {
form.Show();
}
When you are ready to update FormA, call your member function.
this.m_FormA.FillEmployeeGrid(empAdd);
Once you have all this working, you should not have a need to call Refresh() to update the UI unless something is going to be blocking the UI thread (in which you may want to do some asynchronous anyway).

When you call NewEmployee emp = new NewEmployee(); in form b you are creating a reference to a NEW instance of FORM A (which is 'NewEmployee', right?) but you never actually SHOW this instance. When you invoke emp.FillAddressGrid(empAdd); you are acting on a hidden instance NOT the one which you can see.
When Your create an your instance of form B you need to pass a reference to form B like:
FormB formB = new FormB();
formB.Owner = this;
fromB.show();
This will give you the ability to later call:
((NewEmployee)Owner).FillAddressGrid(empAdd);
from Form B.

so u getting data from form B to form A,
Store recieved data in one variable and assign that variable to the textbox.
like,
textbox1.text=v.tostring();

Related

How to access the same object from another Form C#? [duplicate]

I would like to set comboBox.SelectedValue when I select the row in my dataGridView on first form to populate comboBox with that value on another form,
On second form in my load event I have comboBox.DataSource, DisplayMember, ValueMember set it correctly but nothing is happening when I set selectedValue on first. Everything works great when I do it on one form
Form in Windows Forms is a class like other C# classes. The way of communicating between forms are the same as classes. You can consider this options when communicating between classes:
Manipulate second Form from first Form
You can add suitable parameters to the constructor of the second form. Then you can pass values to the constructor when creating an instance of the second form. In the second form store parameters in member fields and use them when you nees.
You can create public property or method in the second form and set those properties after creating an instance of the second form. This way you can use them when you need in the second form. This option is not limited to passing values when creating the second form. You can even use that property during the execution of second Form. Also it's useful for getting a value from it.
As another option you can make the control which you want to manipulate it public and this way you can access to it from other form. Using a method is a more recommended way of doing this.
Manipulate first Form from second form
You can create a public method or property in first form and pass an instance of the first form to second form. Then using that method/property on the passed instance, you can manipulate the first form.
You can create an event in second form and after creating an instance of second form subscribe for it in first form and put the code for changing the form in the handler. Then it's enough to raise the event in second form.
You can define a public property of type Action or some other delegate type in second form and then after creating an instance of second form, assign the property using a custom action. Then in second form, it's enough to invoke the action when you need to manipulate first form.
Also here you can make a control of first form to be public and then if you pass an instance of the first form to the second form, you can manipulate the control. It's recommended to use other solutions. It's like creating public property or method, but a method which performs specific task on the control is better that exposing the whole control. But you may need this solution some times.
Here are some useful examples about above solutions.
Manipulate second Form from first Form
Example1 - Using constructor of second Form
Use this example when you need to pass some data to second form, when creating the second form.
public partial class Form2 : Form
{
int selectedValue;
public Form2(int value)
{
InitializeComponent();
selectedValue = value;
}
private void Form2_Load(object sender, EventArgs e)
{
//Load data
this.comboBox1.DataSource = new MyDbContext().Categories.ToList();
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedValue = selectedValue;
}
}
Then in your first form, it's enough to pass the value to Form2 when you create a new instance of it:
var value = 2; // Or get it from grid
var f = new Form2(value);
f.ShowDialog();
Example2 - using public Property or Method of second Form
Use this example when you need to pass some data to second form, when creating or even after creation of second form.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string SomeValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
Then in your first form, it's enough to pass the value to Form2 when you need, after creating Form2 or whenever you need to set value of textBox1 on Form2:
var f = new Form2(); //value is not needed here
f.SomeValue = "some value";
f.Show();
//...
f.SomeValue = "some other value";
Example 3 - Making a Control of Second form public
Use this example when you need to change a property of a control on second form, when creating or even after creation of second form. It's better to use public property or method instead of exposing whole control properties.
In your Form, at designer, select the control and in Properties window set the Modifiers property to Public. Also make sure the GenerateMember property is true. Then you can simply access this control using its name from outside of the Form.
var f = new Form2();
f.textBox1= "some value";
Manipulate first Form from second form
Example 4 - Create public Method or Property in first Form and pass an instance of First Form to constructor of second Form
Use this example when you need to change first Form from second Form.
In your Form1, create a property of a method that accepts some parameters and put the logic in it:
public void ChangeTextBox1Text(string text)
{
this.textBox1.Text = text;
}
Then create a constructor in Form2 which accepts a parameter of type Form1 and keep the passed value in a member field and use it when you need:
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.ChangeTextBox1Text("Some Value");
}
Now when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();
Example 5 - Using event of second Form in first Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 6 - Injection an Action in second Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 7 - Making a Control of first form public
In this solution you need to make a control in first form public, like example 3. Then like example 4 pass an instance of the first form to second form and keep it in a field and use it when you need. Using a public method or property is preferred.
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.textBox1.Text = "Some Value";
}
when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();

c# passing string to different form textbox [duplicate]

I would like to set comboBox.SelectedValue when I select the row in my dataGridView on first form to populate comboBox with that value on another form,
On second form in my load event I have comboBox.DataSource, DisplayMember, ValueMember set it correctly but nothing is happening when I set selectedValue on first. Everything works great when I do it on one form
Form in Windows Forms is a class like other C# classes. The way of communicating between forms are the same as classes. You can consider this options when communicating between classes:
Manipulate second Form from first Form
You can add suitable parameters to the constructor of the second form. Then you can pass values to the constructor when creating an instance of the second form. In the second form store parameters in member fields and use them when you nees.
You can create public property or method in the second form and set those properties after creating an instance of the second form. This way you can use them when you need in the second form. This option is not limited to passing values when creating the second form. You can even use that property during the execution of second Form. Also it's useful for getting a value from it.
As another option you can make the control which you want to manipulate it public and this way you can access to it from other form. Using a method is a more recommended way of doing this.
Manipulate first Form from second form
You can create a public method or property in first form and pass an instance of the first form to second form. Then using that method/property on the passed instance, you can manipulate the first form.
You can create an event in second form and after creating an instance of second form subscribe for it in first form and put the code for changing the form in the handler. Then it's enough to raise the event in second form.
You can define a public property of type Action or some other delegate type in second form and then after creating an instance of second form, assign the property using a custom action. Then in second form, it's enough to invoke the action when you need to manipulate first form.
Also here you can make a control of first form to be public and then if you pass an instance of the first form to the second form, you can manipulate the control. It's recommended to use other solutions. It's like creating public property or method, but a method which performs specific task on the control is better that exposing the whole control. But you may need this solution some times.
Here are some useful examples about above solutions.
Manipulate second Form from first Form
Example1 - Using constructor of second Form
Use this example when you need to pass some data to second form, when creating the second form.
public partial class Form2 : Form
{
int selectedValue;
public Form2(int value)
{
InitializeComponent();
selectedValue = value;
}
private void Form2_Load(object sender, EventArgs e)
{
//Load data
this.comboBox1.DataSource = new MyDbContext().Categories.ToList();
this.comboBox1.DisplayMember = "Name";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedValue = selectedValue;
}
}
Then in your first form, it's enough to pass the value to Form2 when you create a new instance of it:
var value = 2; // Or get it from grid
var f = new Form2(value);
f.ShowDialog();
Example2 - using public Property or Method of second Form
Use this example when you need to pass some data to second form, when creating or even after creation of second form.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string SomeValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
Then in your first form, it's enough to pass the value to Form2 when you need, after creating Form2 or whenever you need to set value of textBox1 on Form2:
var f = new Form2(); //value is not needed here
f.SomeValue = "some value";
f.Show();
//...
f.SomeValue = "some other value";
Example 3 - Making a Control of Second form public
Use this example when you need to change a property of a control on second form, when creating or even after creation of second form. It's better to use public property or method instead of exposing whole control properties.
In your Form, at designer, select the control and in Properties window set the Modifiers property to Public. Also make sure the GenerateMember property is true. Then you can simply access this control using its name from outside of the Form.
var f = new Form2();
f.textBox1= "some value";
Manipulate first Form from second form
Example 4 - Create public Method or Property in first Form and pass an instance of First Form to constructor of second Form
Use this example when you need to change first Form from second Form.
In your Form1, create a property of a method that accepts some parameters and put the logic in it:
public void ChangeTextBox1Text(string text)
{
this.textBox1.Text = text;
}
Then create a constructor in Form2 which accepts a parameter of type Form1 and keep the passed value in a member field and use it when you need:
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.ChangeTextBox1Text("Some Value");
}
Now when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();
Example 5 - Using event of second Form in first Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 6 - Injection an Action in second Form
Take a look at this post. It's about communication between form and a control, but it's applicable to communication between forms also.
Example 7 - Making a Control of first form public
In this solution you need to make a control in first form public, like example 3. Then like example 4 pass an instance of the first form to second form and keep it in a field and use it when you need. Using a public method or property is preferred.
Form1 form1;
public Form2 (Form1 f)
{
InitializeComponent();
form1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.textBox1.Text = "Some Value";
}
when creating Form2 you should pass an instance of Form1 to it:
var f = new Form2(this);
f.Show();

Method call from another form

I am trying to call a method on my parent form from a child form, which in turn calls a method in my custom user control. I am able to make the call if I do this...
In child form:
private void btnSaveNode_Click(object sender, EventArgs e)
{
frmMain frm = new frmMain();
frm.getNodeData(txtPartName.Text);
this.Hide();
}
In parent form:
public void getNodeData(string partNbr)
{
string strPartNbr = partNbr;
buildNode(strPartNbr);
}
public void buildNode(string partNbr)
{
drewsTreeView tv = new drewsTreeView();
tv.addNode(partNbr);
}
And finally, the method in the user control
public void addNode(string strPartNbr)
{
btnNode.Location = new Point(13, 13);
btnNode.Width = 200;
btnNode.Height = 40;
//btnNode.Text = strPartNbr;
btnNode.Text = "Testing";
this.Controls.Add(btnNode);
btnNode.Click += btnNode_Click;
}
So my problem is, the button does not get built in the addNode() method. If I call the method in the onLoad event of the main form, it builds just fine. I ran in debug mode, and I can see the method is getting called and the correct parameters are getting passed.
So why will it build the button when called from the parent, but not when called from the child?
One way to do this is to pass in your instance of frmMain to the Form.Show() method:
// ... in frmMain, displaying the "child" form:
frmChild child = new frmChild(); // <-- whatever your child type is
child.Show(this); // passing in a reference to frmMain via "this"
Now over in your child form code, you can cast the Form.Owner property back to your frmMain type and do something with it:
private void btnSaveNode_Click(object sender, EventArgs e)
{
frmMain frm = (frmMain)this.Owner;
frm.getNodeData(txtPartName.Text);
// ...
}
In general, if you instantiate a form in a method call and you don't do something with it like save it to an instance variable or Show() it then you're making a mistake. That form is never seen by the user and just gets garbage collected after your method exits.
Also, you are modifying the same button in basically the same way and adding it to the same form multiple times. Don't do this. Learn about reference semantics.
If you want your child form to be able to cause something to happen in the parent form, you could have the parent give a reference to itself to the child. It would be better to have the parent provide a delegate to the child that the child can invoke as needed.

how to automatically refresh data from database with datagridview in c#

I have a program that has two forms, Form A is accessible by an admin and Form B is for random users.
Form A is used for searching for the list of registered users.
Form B is used for registering.
Form A has datagridview that has data from database, I want the datagridview to refresh the data inside it automatically, after someone registered from Form B...
I want to get the data from the database and put it into datagridview automatically without closing the form and opening it again...
sorry i'm still new at this.. Can you give me some advice and examples please...
Thank you...
Without any code is difficult to answer your problem. But usually this kind of problem could be resolved implementing a simple form of event handling.
In your case FormB publishes the information that a new user has been registered. When a new user register itself the FormB checks if anyone has registered itself to be notified of the event. The FormA registers itself to receive the notification of the fact.
In code you have this in FormB
public class FormB : Form
{
public delegate void OnNewUserRegistered(string username)
public OnNewUserRegistered NewUserRegistered;
....
protected void cmdRegister_Click(object sender, EventArgs e)
{
// Code to register the user
string username = txtUserName.Text;
..... etc .....
// If someone has registered a subscription then call that subscription handler
if(NewUserRegistered != null)
NewUserRegistered(username);
}
}
Now the biggest problem, according to your explanation, is the mode in which the FormA subscribes the event in FormB. Suppose that, when the FormA loads, the FormB is already opened. You need to search for the instance of FormB
FormA.cs code
Public FormB RegistrationForm {get; set;}
private void Form_Load(object sender, EventArgs e)
{
// If FormB is open then get its instance
this.RegistrationForm = Application.OpenForms.Cast<Form>().OfType<FormB>().FirstOrDefault ();
if(this.RegistrationForm != null)
{
// Subscribe to the registration event in FormB
RegistrationForm.NewUserRegistered += ANewUserHasBeenRegistered;
// Subscribe to the closed event of FormB
RegistrationForm.Closed += FormBHasBeenClosed;
}
// Now load the current user list in your grid view.
LoadUserList(); // this contains the code that initializes the gridView
}
// this is the subscription method that will be called by the FormB instance
// every time a new user registers with that form
private void ANewUserHasBeenRegistered(string userName)
{
// Here you have two options.
// Reload the grid I.E. call LoadUserList();
// Try to manually add the new user in the current gridview.
.....
}
// this will be called by the framework when FormB instance closes.
// It is important to avoid any possibility to reference a destroyed form
// using the RegistrationForm variable.
private void FormBHasBeenClosed(object sender, FormClosedEventArgs e)
{
this.RegistrationForm = null;
}
The last point to address is the fact that FormB could be opened AFTER the FormA has been opened. This happens probably from some kind of menuItem code that you need to adjust with:
FormB f = new FormB();
// Search if there is an instance of FormA around
// If found then pass the instance of the FormB to the RegistrationForm public property of FormA
FormA currentFormA = Application.OpenForms.Cast<Form>().OfType<FormA>().FirstOrDefault ();
if(currentFormA != null)
currentFormA.RegistrationForm = f;
// Allow users to register.....
f.ShowDialog();

passing something from child form to parent

so i have this form and on it is a combo box populated from a database via a SQL method.
and i have another form which allows us to maintain the database table etc.
so i make a new instance of the second form doing:
Form1 frm = new Form2;
frm.show();
once i have done what ever i wanted to do on the second form and i close it, i need to somehow trigger an event or something which will refresh the combo box and the code behind it.
i was thinking of some onchange or focus event for the whole form, the problem is i have 5 of these combo boxes and running all the SQL again.
i also thought of passing somesort of variable thro but then i would still need an event for that.
any ideals would be awesome
I think you had your answer in the question... Use an event / handler to refresh.
E.g.
public class Form2 : Form
{
public event EventHandler DbChanged;
protected virtual void OnDbChanged()
{
... // Raise event
}
// On OK button/FormClosing/Closed whatever, be sure to call OnDbChanging
}
Then in your Form1 code
var form2 = new Form2();
form2.DbChanged += new EventHandler(Form2_DbChanged); // Add method to handle change and update the appropriate combo box
form2.Show();
If you've assigned these forms with the first form owning the second, like this:
Form2 frm2 = new Form2();
//assuming that you're launching this form from within the first form
frm2.Owner = this;
then you can get a reference to the first form through the Owner property, and thus call methods on it.
Form2_FormClosed(object o, FormClosedEventArgs e)
{
this.Owner.updateComboBox();
}
Note that you'll need the FormClosing event if you want to send data from the form's controls back, though.
Note that the Owner property has some other special characteristics. Notably, the child form will remain showing (on top) when the parent form is selected.
You can use delegate and event here.
Your parent class will create an object of child class and will also subscribe to the event if child class.
Whenever child class need to pass something/ signal parent class, it will raise an event.
As parent has subscribed to these event, it it will get that data and do the required operation.
Hope this helps you.
Forms are classes. Like any other class, they can have properties and events.
Your Form2 can expose a "DatabaseChanged" event. Form1 or any other form that cares can subscribe to that event. When the database changes, Form2 can fire that event, Form1 will see it and update the combo box.
Lots of options, but a simple one is passing the main form as a reference to the second form.
Form2 frm = new Form2( this );
frm.Show();
Then when Form2 finishes its work, it can call some method on the main form to update
public class Form2 : Form
{
public Form2( Form1 form1 )
{
this.form1 = form1;
}
/// ...
public void Work()
{
// ...
form1.Update( someData );
}
}
Not necessarily ideal from a maintenance perspective, but workable for small apps.
Suppose your combo name id cmb1 and
cmb1.DataSource = ds1;
and you need to call a new window do some work there & whenever you close that window your parent will refresh or cmb1 will have the latest data.
from you parent window call your chlid window like this
if (NameOfWindow.RequestAction(ref ds1)) // let RequestAction is a method
{
///refresh your data source of combo
}
and in the child window the method should be like this:
public static bool RequestAction(ref ds1)
{
NameOfWindow frm = new NameOfWindow();
if (frm.ShowDialog() == DialogResult.OK)
{
//do what ever you want to do and update the ds1
return true;
}
else
{
return false;
}
}

Categories