I want that when I insert or update records in another form (Form2), the DataGridView on Form1 should automatically refresh (call btnRefresh) after each operation or preferably wait until all change operations have finished, and update the DataGridView form Form2's closing event with all changes.
I believe in VB.NET this is achieved with Form1.DataGridView.Refresh, but I am not sure in C#. I was told that I pass the reference of the DataGridView on Form1 to Form2 using properties but since I'm new to C#, I didn't know how to. How can I resolve this issue?
My refresh button code:
private void btnRefresh_Click(object sender, EventArgs e)
{
GVThesis.DataSource = thesisRepository.GetThesis();
GVThesis.Refresh();
}
Firs, wrap your refresh code into a method of its own, and call that from your click event handler method, like so:
private void btnRefresh_Click(object sender, EventArgs e)
{
this.RefreshData();
}
public void RefreshData()
{
GVThesis.DataSource = thesisRepository.GetThesis();
GVThesis.Refresh();
}
Then, asuming you are instantiating and launching the new form (Form2) from your Form1, simply go into the code of Form2 and create yourself a new constructor overload which will accept a reference to Form1, and store it in a private variable, like so:
public partial class Form2 : Form
{
private Form1 frm1;
public Form2()
{
InitializeComponent();
}
public Form2(Form1 otherForm)
{
InitializeComponent();
this.frm1 = otherForm;
}
}
Then you can call the "refresh" from anywhere you like in Form2 like so:
this.frm1.RefreshData();
EDIT:I created a small sample, I cannot upload it here...but here is a screenshot of both the program itself in VS, as well as a screenshot of the result of running it and performing the function...hopefully that will help.
The program (zoom your view if it appears too small)
The Result:
Related
Is there a way I can call a function that is present in the parent form (users), where an instance of a second form(addNewUser) is called? What I want to do is when the second form closes, to execute a function in the parent form (users) which is updating a table so that the changes done in the second one (addNewUser) are updated in the table in the first form (users).
a simple drawing of what I am trying to achieve
With an event driven paradigm like WinForms the best path is to use the events when there is one that you can intercept.
You can subscribe to an event from any class that creates instances of the event raiser. In this case you could simply bind an event handler to the FormClosed event raised by the second form.
// Suppose you have a button click that opens the second form.
private void button_Click(object sender, EventArgs e)
{
SecondForm f = new SecondForm();
f.FormClosed += onSecondFormClosed;
f.ShowDialog();
}
private void onSecondFormClosed(object sender, FormClosedEventArgs e)
{
// Do whatever you need to do when the second form closes
}
Define global variables to identify your instances of your forms:
internal static Form1 CurrentForm1 { get; set; }
internal static Form2 Frm2 { get; set; }
Then affect the variables as follows:
public Form1()
{
InitializeComponent();
CurrentForm1 = this;
}
Somewhere in your code, you'll define the Form2:
Frm2 = new Form2();
Now, from the Frm2 code, you'll access to the form1 non static methods with:
Form1.CurrentForm1.UpdateMyThings();
And from the Frm1 code, you'll be able to watch the things on Frm2, like:
bool notified = false;
while (Frm2.backgroundWorker1.IsBusy)
{
if (notified == false)
{
Message("Please wait...");
notified = true;
}
Application.DoEvents();
}
In this example, Frm1 checks if the backgroundworker #1 is still running in Frm2 (The Message function may display the message in a label or something).
I have following problem:
I have a Form1 where I open a second Form2 from it. Now I have a save Button in Form2 where entries from Textboxes are saved to a csv file. But I want to save some entries from Form1 too. The Textbox entries from Form2 are getting saved but entries from Form1 are empty strings. Following code:
In Form1:
public void showInputToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
}
to open the second Form via the first one and functions to grab the entries from the Form1 Textboxes:
public String getLocation()
{
return LocationBox.Text;
}
public String getFilesLoc()
{
return FilesLocation.Text;
}
In Form2 I have the following:
private Form1 m_form = null;
public Form2(Form1 f)
{
InitializeComponent();
m_form = f;
}
and then the function to grab the entries and save them:
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
proc.setParams(form1.getLocation(),getFilesLoc());
proc.saveCurrentSettings();
}
I left the other parameters out. So entries from Form2 are read correctly but the ones from Form1 are just an empty string (""). What can I do?
In the click handler, you're creating a new Form1 here:
Form1 form1 = new Form1();
That will have empty values - but you want the value from the existing form which you kept a reference to in your constructor - so use it!
private void button1_Click(object sender, EventArgs e)
{
proc.setParams(m_form.getLocation(), m_form.getFilesLoc());
proc.saveCurrentSettings();
}
(I'd strongly advise you to start following .NET naming conventions, quite possibly turning those get methods into properties, and also considering passing the values into your Form2 constructor instead of the Form1 reference itself. It depends on whether you need to "see" any changes made to Form1 after the construction of Form2.)
use
proc.setParams(m_form.getLocation(), m_form.getFilesLoc());
proc.saveCurrentSettings();
you are not using the reference of Form1 but creating a new object and using that.
Well normally I am quite good at figuring and researching problems without guidance however I have come across a snag. I am trying to create an "Event" with C# (which I have not done before) everything I have looked up has nothing to do with what I need.
I am trying to call a class on my main form when form2 is hidden. I found some code which was supposed to check to see if form2 closed - Either I didn't integrate it into my code properly or closing is different to hiding.
So just to clarify I want to run through the program like this:
Form1 runs
Click setting button on Form1 which opens Form2
Form2 opens where settings can be changed
Click the "Ok" button on Form2 (here is where I want Form1 to realise Form2 has been hidden
Hide form one and run a class called Refresh which refreshes button names and URLs
Also,
you can use VisibleChanged event in Form2
private Form2_VisibleChanged(object sender, EventArgs e)
{
if (!this.Visible) { Refresh(); }
}
This might be more elegant...
Open the second form as modal
Form2 form2 = new Form2();
DialogResult result = form2.ShowDialog();
check the result and refresh:
if (result == DialogResult.OK)
Refresh();
What you also need to do in this case is when closing the form set DialogResult of the form, for example if you have an OK button, in the button handler set:
this.DialogResult = DialogResult.OK;
This will automatically close the form as well as I remember correctly.
What you can also do is set DialogResult.Cancel on cancel button if you need that.
If I understand correctly, you want to have a class that stores settings information that both Form1 and Form2 can access. Let's call that class Form1Settings, and implement as:
public static class Form1Settings
{
public static string ButtonText;
public static string Uri;
}
For simplicity, I made this class and its properties static, so both Form1 and Form2 have direct access to it, removing the need for a refresh method.
Form1 would call Form2 in a blocking way, and only update its display if the OK button was clicked.
public partial class Form1 : Form
{
private Form2 form2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void buttonSettings_Click(object sender, EventArgs e)
{
if (form2.ShowDialog() == DialogResult.OK)
{
this.button1.Text = Form1Settings.ButtonText;
this.textBoxUrl.Text = Form1Settings.Uri;
this.Update();
}
}
}
And finally, Form2 will update the settings values with input from the user:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void buttonOK_Click(object sender, EventArgs e)
{
Form1Settings.ButtonText = this.textBoxButton.Text;
Form1Settings.Uri = this.textBoxUri.Text;
this.DialogResult = DialogResult.OK;
this.Hide();
}
}
Why not open Form2 as a modal dialog using ShowDialog()? That way you may return a value if Form2 was closed by OK or by Cancel and act accordingly in Form1 after the call returned.
I am quite new to windows forms. I would like to know if it is possible to fire a method in form 1 on click of a button in form 2?
My form 1 has a combobox. My form 2 has a Save button. What I would like to achieve is:
When the user clicks on Save in form 2, I need to check if form 1 is open. If it is open, I want to get the instance and call the method that would repopulate the combo on form 1.
I would really appreciate if I get some pointers on how I can do work this out. If there any other better way than this, please do let me know.
Thanks :)
Added:
Both form 1 and form 2 are independent of each other, and can be opened by the user in any order.
You can get a list of all currently open forms in your application through the Application.OpenForms property. You can loop over that list to find Form1. Note though that (in theory) there can be more than one instance of Form1 (if your application can and has created more than one instance).
Sample:
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(Form1))
{
((Form1)form).Close();
}
}
This code will call YourMethod on all open instances of Form1.
(edited the code sample to be 2.0-compatible)
Of course this is possible, all you need is a reference to Form1 and a public method on that class.
My suggestion is to pass the Form1 reference in the constructor of Form2.
What you can do is create static event in another class and then get Form 1 to subscribe to the event. Then when button clicked in Form 2 then raise the event for Form 1 to pick up on.
You can have declare the event in Form 1 if you like.
public class Form1 : Form
{
public static event EventHandler MyEvent;
public Form1()
{
Form1.MyEvent += new EventHandler(MyEventMethod);
}
private void MyEventMethod(object sender, EventArgs e)
{
//do something here
}
public static void OnMyEvent(Form frm)
{
if (MyEvent != null)
MyEvent(frm, new EventArgs());
}
}
public class Form2 : Form
{
private void SaveButton(object sender, EventArgs e)
{
Form1.OnMyEvent(this);
}
}
In Visual C# when I click a button, I want to load another form. But before that form loads, I want to fill the textboxes with some text. I tried to put some commands to do this before showing the form, but I get an error saying the textbox is inaccessible due to its protection level.
How can I set the textbox in a form before I show it?
private void button2_Click(object sender, EventArgs e)
{
fixgame changeCards = new fixgame();
changeCards.p1c1val.text = "3";
changeCards.Show();
}
When you create the new form in the button click event handler, you instantiate a new form object and then call its show method.
Once you have the form object you can also call any other methods or properties that are present on that class, including a property that sets the value of the textbox.
So, the code below adds a property to the Form2 class that sets your textbox (where textbox1 is the name of your textbox). I prefer this method method over making the TextBox itself visible by modifying its access modifier because it gives you better encapsulation, ensuring you have control over how the textbox is used.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string TextBoxValue
{
get { return textBox1.Text;}
set { textBox1.Text = value;}
}
}
And in the button click event of the first form you can just have code like:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.TextBoxValue = "SomeValue";
form2.Show();
}
You can set "Modifiers" property of TextBox control to "Public"
Try this.. :)
Form1 f1 = (Form1)Application.OpenForms["Form1"];
TextBox tb = (TextBox)f1.Controls["TextBox1"];
tb.Text = "Value";
I know this was long time ago, but seems to be a pretty popular subject with many duplicate questions. Now I had a similar situation where I had a class that was called from other classes with many separate threads and I had to update one specific form from all these other threads. So creating a delegate event handler was the answer.
The solution that worked for me:
I created an event in the class I wanted to do the update on another form. (First of course I instantiated the form (called SubAsstToolTipWindow) in the class.)
Then I used this event (ToolTipShow) to create an event handler on the form I wanted to update the label on. Worked like a charm.
I used this description to devise my own code below in the class that does the update:
public static class SubAsstToolTip
{
private static SubAsstToolTipWindow ttip = new SubAsstToolTipWindow();
public delegate void ToolTipShowEventHandler();
public static event ToolTipShowEventHandler ToolTipShow;
public static void Show()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = true;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
public static void Hide()
{
// This is a static boolean that I set here but is accessible from the form.
Vars.MyToolTipIsOn = false;
if (ToolTipShow != null)
{
ToolTipShow();
}
}
}
Then the code in my form that was updated:
public partial class SubAsstToolTipWindow : Form
{
public SubAsstToolTipWindow()
{
InitializeComponent();
// Right after initializing create the event handler that
// traps the event in the class
SubAsstToolTip.ToolTipShow += SubAsstToolTip_ToolTipShow;
}
private void SubAsstToolTip_ToolTipShow()
{
if (Vars.MyToolTipIsOn) // This boolean is a static one that I set in the other class.
{
// Call other private method on the form or do whatever
ShowToolTip(Vars.MyToolTipText, Vars.MyToolTipX, Vars.MyToolTipY);
}
else
{
HideToolTip();
}
}
I hope this helps many of you still running into the same situation.
In the designer code-behind file simply change the declaration of the text box from the default:
private System.Windows.Forms.TextBox textBox1;
to:
protected System.Windows.Forms.TextBox textBox1;
The protected keyword is a member access modifier. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member (for more info, see this link).
I also had the same doubt, So I searched on internet and found a good way to pass variable values in between forms in C#, It is simple that I expected. It is nothing, but to assign a variable in the first Form and you can access that variable from any form. I have created a video tutorial on 'How to pass values to a form'
Go to the below link to see the Video Tutorial.
Passing Textbox Text to another form in Visual C#
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
TextBox txt = (TextBox)frm.Controls.Find("p1c1val", true)[0];
txt.Text = "foo";
}