Save the state of a form with PictureBox? - c#

I have a small program in winforms; it's just a program where I can have pictures, but I have a problem. When I have a picture, I close the program and I open it again, the pictures don't stay where I have put them, in the PictureBox.
More simply, I want to keep the state when I close the program, like saving.
Here my code :
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
f.ShowDialog();
var chemin = f.FileName;
pictureBox1.ImageLocation = chemin;
}
}
}
Please help me, I can't go on with this problem...

The simplest way to do this is to use the Application Settings. Right-click on your Project and select Properties. Then go to Settings. In the right hand side, you will see a panel with a grid with only one line. Change Setting in the Name column to ImageLocation and leave the other three values (Type, Scope and Value) as their defaults (string, user and blank).
In design view of your form under properties double-click the FormClosing event to create a new handler. Now enter:
if (pictureBox1.ImageLocation != null)
{
Properties.Settings.Default.ImageLocation = pictureBox1.ImageLocation;
Properties.Settings.Default.Save();
}
Finally in the constructor for the form enter the following after InitializeComponent():
if (Properties.Settings.Default.ImageLocation != null)
{
pictureBox1.ImageLocation = Properties.Settings.Default.ImageLocation;
}
HTH

Related

Enable/Disable Buttons On Owner Form When Owned Form Is Closed

I am working on a WinForms Desktop application in C# .NET. The target framework is .NET Framework 4.8. When the application is started, the main form is displayed with several buttons. Each button hides the main form when clicked and opens another form that displays data with which the user interacts. The main form is the owner of the new form.One button opens a form that presents a list of files from a network share folder in a data grid view. The user selects a row in the data grid and clicks a button to import the information in the file to various tables in a SQL Server database. When the import is complete, the selected row is removed from the data grid. When the user closes this form, there is code in the Form Closed event to show the owner. This all works well.My problem is that when the main form is unhidden, I need to disable the button that opens the form to list files to import if there are not any files in the network share folder to be imported. There is also a line of code to change the button's text property informing the user there are not any files to import.I realize I can place the code to disable the button and change button text in the VisibleChanged event. But, I only want the code to run after the owned form's closed event shows the owner form. How do I enclose the code in the main form's VisibleChanged event to disable the file import button only after the owned form is closed. Or, is it possible to edit the properties of the button on the owner form in the Form Closed event prior to the Owner.Show();I found a similar question WinForm Form Closed Event. But when I follow the suggestion
private void LoadChildForm_Click(object sender, EventArgs e)
{
ChildForm form = new ChildForm();
form.FormClosed += new FormClosedEventHandler(ChildFormClosed);
form.Show();
}
substituting my names
private void btnImportHFR_Click(object sender, EventArgs e)
{
Form form = new frmHFRFiles();
form.FormClosed += new FormClosedEventHandler(frmHFRFiles_FormClosed);
form.Show(this);
Hide();
}
Visual Studio flags frmHFRFiles_FormClosed as an error for the name does not exist in the current context.
ChildForm form = new ChildForm(this);
Then in ChildForm constructor:
MainForm m_MainForm;
Public ChildForm (MainForm mainForm)
{
m_MainForm = mainForm;
}
Then in closing event:
m_MainForm.button1.Enabled = false;
Ensure button1 is public
Here is what I did. I created a boolean variable in the main form and set the initial value to false.
private bool updateButtons = false;
The main form's constructor executes the search for files in the network folder.
public frmMainMenu()
{
InitializeComponent();
Shared.FilesForImport = GetHFRFiles();
}
The form's load event calls the EnableButtons() method
public void EnableButtons()
{
btnImportHFR.Enabled = Convert.ToBoolean(Shared.FilesForImport.Count);
btnImportHFR.Text = btnImportHFR.Enabled ? "Find Available HFR" : "No HFR For Import";
btnGetFacilityStatus.Enabled = Shared.sqlWrap.GetDataForFacStat(Shared.DsFacStat);
updateButtons = false;
}
The main form's visible changed event fires after the form load event. The network folder is not searched again because the updateButtons value is set to false.
private void frmMainMenu_VisibleChanged(object sender, EventArgs e)
{
if(updateButtons)
{
EnableButtons();
}
}
In the button click event, the updateButtons value is set to true after the main form is hidden.
private void btnImportHFR_Click(object sender, EventArgs e)
{
frmHFRFiles form = new frmHFRFiles();
form.Show(this);
Hide();
updateButtons = true;
}
The child form's closed event calls the Owner.Show() method
private void frmHFRFiles_FormClosed(object sender, FormClosedEventArgs e)
{
Owner.Show();
}
This causes the main form's visible changed event to fire. Only this time the EnableButtons() method will run because the updateButtons value is true.
private void frmMainMenu_VisibleChanged(object sender, EventArgs e)
{
if(updateButtons)
{
EnableButtons();
}
}
public void EnableButtons()
{
btnImportHFR.Enabled = Convert.ToBoolean(Shared.FilesForImport.Count);
btnImportHFR.Text = btnImportHFR.Enabled ? "Find Available HFR" : "No HFR For Import";
btnGetFacilityStatus.Enabled = Shared.sqlWrap.GetDataForFacStat(Shared.DsFacStat);
updateButtons = false;
}
Finally, the EnableButtons() method sets the updateButtons value to false.
It seems rudimentary to me, but it works. Thank you everyone for your feedback.
My problem is that when the main form is unhidden, I need to disable the button that opens the form to list files to import if there are not any files in the network share folder to be imported. There is also a line of code to change the button's text property informing the user there are not any files to import.
So your main form has a button X. If this button is clicked a method is called. This method will first hide the form, then show the subform until the subform is closed. The method should disable button X, change the button's text and unhide the form.
To make this flexible, we won't do everything in one procedure, we make several procedures with the intention of the procedure: "Inform operator there are no files to import" "Disable opening the subform", and of course their counterparts "Enable opening the subform", "Inform operator there are files to import"
TODO: invent proper method names
private void ShowNoFilesToImport()
{
this.buttonX.Text = ...;
}
private void DisableOpeningSubForm()
{
this.buttonX.Text.Enabled = false;
}
The advantage of this, is that if you later want to change the way that you want to inform the operator, for instance if you want to use an information field at the bottom of you screen, you will only have to change this in one place.
Furthermore, you can reuse the procedures, for instance you can add a menu item that will do the same as button X, this menu item can call the same methods
private void PerformActionsButtonX() // TODO: invent proper name
{
// Hide this form, and show the Subform until it is closed
this.Visible = false;
using (var dlg = new SubForm())
{
// if needed, set properties of the subForm:
dlg.Text = ...
dlg.Position = ...
// show the form until it is closed
var dlgResult = dlg.ShowDialog();
this.ProcessDlgResult(dlgResult, dlg);
}
// Show that there are no files to Import and disable OpeningSubform
this.ShowNoFilesToImport();
this.DisableOpeningSubform();
// Finally: show this form:
this.Visible = true;
}
And of course call this method when ButtonX or menu item Y are clicked:
private void OnButtonX_Clicked(object sender, ...)
{
this.PerformActionsButtonX();
}
private void OnMenyItemYClicked(object sender, ...)
{
this.PerformActionsButtonX();
}

c# Opening up a form depending on the linklabel name

I have a combobox that dictates the linklabel name, I would like to select the linklabel depending on the name of it. Here is what I have done so far. First part of the if statement works but the second does not.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if((string)linkLabel1.Text == "Advanced Software Engineering")
{
Form4 g = new Form4();
g.Show();
}
else if((string)linkLabel1.Text == "Web Research")
{
Form5 g1 = new Form5();
g1.Show();
}
}
What exactly is the problem? Your approach would work fine.
However I would create my own FormBase that has a property called "LinkLabel"
Each WinForm would then set the LinkLable its designed to be used by.
Then in your LinkClicked event do something like this
foreach(FormBase _base in _Forms)
{
if(_base.LinkLabel == linkLabel1.Text)
{
_base.Show();
break;
}
}
EDIT: This wouldn't work if the event is not called by clicking on linkLable1

Handling data between multiple Forms

I am working on a program that generates a PDF file. Before the final generation of the file, I want to give the user the option to edit a portion of the file (The title of the graph that is about to be created). I want this to show up in a new form when the user clicks a button to export the PDF. Here is an outline of what I am trying to do...
private void button4_Click(object sender, EventArgs e) // Test PDF Code!
{
Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.ToString().Length - 4));
NewPDF.Show();
if (NewPDF.Selected == true)
{
// Create PDF, open save file dialog, etc
}
}
And here is the Form that is being opened by this button click...
public partial class Form2 : Form
{
public bool Selected
{
get;
set;
}
public String GraphName
{
get;
set;
}
public Form2(String FileName)
{
InitializeComponent();
textBox1.Text = FileName;
GraphName = FileName;
Selected = false;
}
public void button1_Click(object sender, EventArgs e)
{
GraphName = textBox1.Text;
this.Selected = true; // After the button is selected I want the code written above to continue execution, however it does not!
}
}
As of now, when I click on the button in Form2, nothing happens, there is something about the communication between the two Forms that I am not understanding!
You should change your Form2.GraphName like below
public String GraphName
{
get { return textBox1.Text }
}
then change your new Form2 creation like below, test it since I haven't run this through VS, but should work :)
private void button4_Click(object sender, EventArgs e) // Test PDF Code!
{
// why on earth were you doing .Text.ToString()? it's already string...
Form2 NewPDF = new Form2(chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Substring(0, chart3.Titles[chart3.Titles.IndexOf("Header")].Text.Length - 4));
// show as a dialog form, so it will wait for it to exit, and set this form as parent
NewPDF.ShowDialog(this);
if (NewPDF.Selected == true)
{
// get the name from the other form
string fileName = NewPDF.GraphName;
// Create PDF, open save file dialog, etc
}
}
The answer to your problem is quite simple.
NewPDF.Show();
Show() does not pause execution of the calling form. Therefore, the check underneath that that verifies the Selected property if true will never execute properly, since that check is reached and verified just as the form starts appearing. ShowDialog() does pause execution and waits for the called form to close.
That aside; I would recommend one of two other ways to communicate between forms;
Use a global variable. Declare a variable holding the graph's name somewhere in a public module. Call the dialog that asks the user to input a name with ShowDialog(), since that pauses execution of the calling form until the called form returns a result.
if(Form.ShowDialog() == DialogResult.OK) {
// Save pdf, using title in global variable
}
Make sure to set the DialogResult in the called form before Close()-ing it.
Pass an instance variable of the calling form to the called name-input form to the constructor and save it. That way, if you expose the graph name property as a public property, you should be able to access it from the called form in the code that closes the form, which is your:
public void button1_Click(object sender, EventArgs e)
{
callingFormInstance.GraphNameProperty = textBox1.Text;
Close();
}
Hope that helps. Cheers!

How to reload form in c# when button submit in another form is click?

I have a combo box in my C# which is place in form named frmMain which is automatically fill when I add (using button button1_Click) a product in my settings form named frmSettings. When I click the button button1_Click I want to reload the frmMain for the new added product will be visible.
I tried using
frmMain main = new frmMain();
main.Close();
main.Show();
I know this code is so funny but it didn't work. :D
This is windows form!
EDIT
Please see this image of my program for better understanding.
This is my frmMain
Here is what my settings frmSettings form look like. So, as you can see when I click the submit button I want to make the frmMain to reload so that the updated value which I added to the settings will be visible to frmMain comboBox.
Update: Since you changed your question here is the updated version to update your products
This is your products form:
private frmMain main;
public frmSettings(frmMain mainForm)
{
main = mainForm;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
main.AddProduct(textBox1.Text);
}
It will need the mainform in the constructor to pass the data to it.
And the main form:
private frmSettings settings;
private List<string> products = new List<string>();
public frmMain()
{
InitializeComponent();
//load products from somewhere
}
private void button1_Click(object sender, EventArgs e)
{
if (settings == null)
{
settings = new frmSettings(this);
}
settings.Show();
}
private void UpdateForm()
{
comboBoxProducts.Items.Clear();
comboBoxProducts.Items.AddRange(products.ToArray());
//Other updates
}
public void AddProduct(string product)
{
products.Add(product);
UpdateForm();
}
You then can call UpdateForm() from everywhere on you form, another button for example.
This example uses just a local variable to store your products. There are also missing certain checks for adding a product, but I guess you get the idea...
this.Close();
frmMain main = new frmMain();
main.Show();
There is no such built in method to set all your values as you desire. As i mentioned in the comment that you should create a method with your required settings of all controls, here is the sample code:
private void ReloadForm()
{
comboBox.ResetText();
dataGridView.Update();
//and how many controls or settings you want, just add them here
}
private void button1_Click(object sender, EventArgs e)
{
ReloadForm(); //and call that method on your button click
}
Try out this code.
this.Refresh();
Application.Doevents();
this.Refresh();
Refresh();
this.Hide();
frmScholars ss = new frmScholars();
ss.Show();
you want to Invalidate the form
http://msdn.microsoft.com/en-us/library/598t492a.aspx
IF you are looking to refresh page from usercontrol .Here is expample where i amrefreshing form from usercontrol
Find the form in which this reload button is.
Then Call invalidiate tab control and refresh it.
Dim myForm As Form = btnAuthorise.FindForm()
For Each c As Control In myForm.Controls
If c.Name = "tabControlName" Then
DirectCast(c, System.Windows.Forms.TabControl).Invalidate()
DirectCast(c, System.Windows.Forms.TabControl).Refresh() 'force the call to the drawitem event
End If
Next
Not required reload for entire form. Just create a function for form initialise.
you can call this function any time. This will refresh the form.
private void acc_Load(object sender, EventArgs e)
{
form_Load();
}
public void form_Load()
{
// write form initialise codes example listView1.Clear();...
}
private void button1_Click(object sender, EventArgs e) //edit account
{
//Do something then refresh form
form_Load();
}
If you want to automatically update the value of the other form when you click the button from another one you can use timer control. Just set the timer to 0.5s in order to update the form fast
I think that, by calling the frmMain_load(sender,e) when you are clicking the button should reload the form.
You may also try to Invalidate() the form just like #Nahum said.

C# and Modal Windows

I have the following situation: The main window where some of the data is completed, it is also a button that opens a new modal window where you choose the product and the range of products, I click OK and move on to the next screen where choose the quantity, price, and after approval of the data which I click OK, I want to have access to the data selected in modal windows in the main window, as it can be done using C #?
You can do something that looks more or less like this:
private void button1_Click(object sender, EventArgs e)
{
Form2 firstPopup = new Form2();
firstPopup.ShowDialog();
var someData = firstPopup.SomeValue;
Form2 secondPopup = new Form2();
secondPopup.ShowDialog();
var someOtherData = secondPopup.SomeValue;
doSomeStuff(someData, someOtherData);
}
In this case SomeValue is a property on the form with a public getter and a private setter. It's value will be set sometime before the form is closed. You can have any number of such properties per form, and any number of forms.
This is similar to the way that Open, Save As and Folder dialogs work. Take for example the Open File Dialog, once you click OK, you have access to the file that was selected
Suggestion:
In your modal window, set some public properties which hold your data. Set your OK button to set the forms DialogResult to OK, in your parent form you can do the following test (in this instance, DataModel is the data you are trying to access)
if(modalWindow.DialogResult == DialogResult.OK)
{
this.DataModel = modalWindow.DataModel;
}
Here is some information on how to use DialogResult
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult.aspx
Typically with a Modal window you follow a similar pattern to that used by the OpenFileDialog, where you do something like this:
public class MyDialog : Form
{
public MyResult Result { get { /* code elided */ } }
}
I.e, in addition to having the modal form's code - you also expose a public Result property of a given type which can provide the data entered on that form's UI (this is better than exposing the controls on the form as it means you are free to change all of that without having to re-code any other forms that depends on it).
You make sure that the Result is guaranteed to be available and valid if the Ok or Yes (whatever the confirmation button is) button is clicked. Then you make sure that you set the DialogResult of the form accordingly (you can assign one to each button as well - e.g. DialogResult.Cancel to a cancel button).
Then when you open your form you do it something like this:
var form1 = new MyDialog();
if(form1.ShowDialog() != DialogResult.OK)
return; //abort the operation, the user cancelled/closed the first modal
MyResult form1Data = form1.Result; //get your actual data from that modal form.
//...and then on with your second modal
So you collect the data from the modal(s) as you go along, aborting if any are cancelled.
Try not using a modal window!
If you call
var dialog = new DialogWindow();
If (dialog.ShowDialog(mainWindow) == DialogResult.OK) {
use the result of the dialog window
}
the dialog window will be modal, which means that you cannot access other windows while it is open.
With the following code, both windows are accessible at the same time. The problem is, however, that the code in the main window is not paused while the dialog runs.
var dialog = new DialogWindow();
dialog.Show(mainWindow);
You cannot use the result of the dialog window here!
Therefore you need a way to communicate the completion of the dialog to the main window. I suggest creating an event in the dialog window for this purpose
public class ProductResultEventArgs : EventArgs
{
public ProductResultEventArgs(List<Product> products)
{
Products = products;
}
public List<Product> Products { get; private set; }
}
In the dialog window
public event EventHandler<ProductResultEventArgs> ProductsChosen;
private void OnProductsChosen(List<Product> products)
{
var eh = ProductsChosen;
if (eh != null) {
eh(this, new ProductResultEventArgs(products));
}
}
private BtnOk_Click(object sender, EventArgs e)
{
OnProductsChosen(somehow get the product list);
}
In the main window you can do something like this
var dialog = new DialogWindow();
dialog.ProcuctsChosen += Dialog_ProductsChosen
dialog.Show(mainWindow);
and create a handler
private Dialog_ProductsChosen(object sender, ProductResultEventArgs e)
{
use e.Products here
}
Note: Passing the main window as parameter to ShowDialog or Show makes the main window owner of the dialog. This means that the dialog window will always stay in front of the main window and cannot disappear behind it. If you minimize the main window, this will minimize the dialog window as well.

Categories