How to use label1 in more Forms? - c#

private void rectangleButton3_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Excel Files only | *.xlsx; *.xls; *.csv;";
ofd.Title = "Choose the file";
if (ofd.ShowDialog() == DialogResult.OK)
label1.Text = ofd.FileName;
}
}
Hi, im trying to use label1 as my path to export .csv file into my project: https://ibb.co/wNbnqbg
and then in my second form im trying to import: https://ibb.co/mRG0q5S
but the problem is this code: https://ibb.co/Gv3fSPv dont know that label1 is.
Im trying to create main page where user choose with which .csv file will be working. After rectangleButton3_click you save that path into label1 and then in second form i want use this path /label1 to import data into datagridview.

You can't use label1 in a different forms because it's a private field of the form so you can't share value through this field. Also Label is a visual component and not intended for data storage.
To share the value between the two forms, you can create a property in the second form that takes the value from first form. You can set the property in the first form after Excel file has been selected.
public class SecondForm : Form
{
private string _filePath;
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
...
}
When you creating a new form you can set the value from label1 or other place. For example if you open the second form immediately after choosing file you can use next code:
private void rectangleButton3_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Excel Files only | *.xlsx; *.xls; *.csv;";
ofd.Title = "Choose the file";
if (ofd.ShowDialog() == DialogResult.OK)
{
SecondForm secondForm = new SecondForm();
secondForm.FilePath = ofd.FileName;
secondForm.Show();
}
}
}
Finally you can read FilePath in the second form because it's a part of your form and the value is already written from the first form.
If you need to access the value between many forms there are two ways to solve it.
"Good" and architecturally correct solution is to pass this value from form to form and to have a property for file path in each form. It's a right way because you will continue to have a loosely coupled architecture and be able to easily modify the code. For example the middle form may start to get the file path in a different way or the composition of the forms itself may change.
"Bad" and hacky solution is a global state with static properties which you can read and write in any place:
public static class ApplicationState
{
private static string _filePath;
public static string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
}
So you can write ApplicationState.FilePath = ofd.FileName or var filePath = ApplicationState.FilePath; in any place of your code. But the problem is that this violates the encapsulation principle, making it difficult to test and modify the code when developing the project because you will have a single value within the entire application.

You probably want to access it from other form or class.
First you have to declare the label as public or anything visible to other files;
The class calling it have to know the Form1 unit, you may need to add it to the uses clause, but I am not sure;
Then you call it by the complete name, for example Form1.label1.Text.

Related

c# openFileDialog1.InitialDirectory from string

Am pretty new to C# and i need some help on a project i make.
I making an application we need. The application is to search our DB2 for the case number given on textbox by user. This is working fine i retrieve all data i need just fine. Now i want to click a button and open file dialog and user can select one of the files that exists in a folder on our win server under the folder that exists and named with the case number given in text box. So the initial directory should be dynamically changed according to the value in the textbox.
On my first attempt i declared the case number on a
string public String Gazm = "155465";
then i called initial directory
openFileDialog1.InitialDirectory = $#"\\apollo\zm\{Gazm}";
and worked fine. Dialogue opened on \\apollo\zm\155465\ and i could choose the files in the folder. I was was happy and i thought that that was easy and that i now have only to change the value of Gazm variable to the one given by user and i will do that easy with:
Gazm = textBox2.Text;
.So i did all happy and when i clicked the button the dialogue opened in the \\apollo\zm\ and not at the \\apollo\zm\Gazm\ where Gazm = textbox.text.
I thought there is something wrong with the string construction so what i tried next is that i made a String foldername = $#"\\apollo\zm\"; and public string fld = ""; . then i edit in button_click where the case number from user is captured the string fld = foldername + azm; and i send this result to be displayed in a textbox to check if the result is the desired.
The result in the textbox was the desired path to the case's number folder but the openfiledialogue will still open on the \\apollo\zm\ where then path in the textbox was the \\apollo\zm\155465\ where 155465 was the case number i typed in the textbox.
As i told you am new in C# and i dont know if what am doing is possible.
Please be kind with noob ;)
i will paste my code now which is only the code that reffers to the openfile dialogue. I made a new solution just for that part so i can do my tests on test solution rather than my main project.
Thank you for any help .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
namespace AutoZhm
{
public partial class Form1 : Form
{
String Gazm = "";
String filename = "";
String foldername = $#"\\apollo\zm\";
public string fld = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
String Gazm = textBox1.Text;
string fld = foldername + azm;
textBox97.Text = fld;
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button4_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = fld;
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox97.Text = openFileDialog1.FileName;
filename = textBox97.Text;
}
}
}
}
You have the fld variables defined twice, once in your class and once within your button1_Click method. I suspect that this is causing you trouble.
The fld variable within the button1_Click is defined as a local variable. Meaning that it only exists within that method. The fld variable defined in your class is not updated by this method as a result, in fact in the code you've shown it well never change from an empty string.
You can easily fix this by removing the type declaration (string fld = [..] to fld = [..]) within the button1_Click method. That will cause the code to use the class defined variable (which the button4_Click_1 can also access).
Now, as you want an adjustment of the input in your TextBox to determine the initial directory, you'll need to set openFileDialog1.InitialDirectory to the current value textBox97.Text.

How pass information between forms involving listView item being changed?

I have file manager program that displays folder in a treeView on the left hand side of a form (frmMain) and files in listView on the left side. I want to be able to select a file (item) from the listView then display the file name in a text on another form with the label = 'Enter a file name.' then rename the file with that new name.
Code from the second form.
public frmRename(string oFile)
{
InitializeComponent();
textBox1.Text = oFile;
}
private void bntOK_Click(object sender, EventArgs e)
{
string nFileName;
nFileName = textBox1.Text;
frmMain fm = new frmMain();
fm.re_nameFile(nFileName);
}
This code runs without any errors; however, when uncommented that is presently commented I get error 'Value of zero is not a valid for index'. I know that this error has talked about a lot; however, I am concern with a different aspect of this error. If I use a line of in private function I don't get this error; whereas, if I use it public function I do. First of all I want to understand why this happens? Second can you tell me how to fix the problem?
So in frmMain you create a new frmRename and in frmRename you create a new frmMain. Bad idea. The new frmMain knows nothing about the original frmMain (including its populated listView).
Solution: in frmMain.bntRename_Click call
rename.ShowDialog();
newFileName = rename.nFileName;
do whatever you want to do with the new name and in frmRename define
public string nFileName {get; private set;}
and further change
private void bntOK_Click(object sender, EventArgs e)
{
nFileName = textBox1.Text;
Close();
}

Save the state of a form with PictureBox?

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

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!

C# After using OpenFileDialog, a MessageBox doesn't open on top

Our primary database application has a feature that exports either an Excel workbook or an Access mdb for specified work orders. Those files are then sent to our subcontractors to populate with the required data. I am building an application that connects to the files and displays the data for review prior to being imported into the primary database. Simple enough, right? Here’s my problem: the application opens a OpenFileDialog box for the user to select the file that will be the datasource for the session. That works perfectly. If I open a MessageBox after it, that box open up behind any other open windows. After that, they respond correctly. I only expect to be using MessageBoxes for error handling, but the problem is perplexing. Has anyone encountered this problem?
The MessageBoxes in the code are only to verify that the path is correct and to solve this problem; but, here’s my code:
private void SubContractedData_Load(object sender, EventArgs e)
{
string FilePath;
string ext;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Access Databases |*.mdb|Excel Workbooks|*.xls";
ofd.Title = "Select the data source";
ofd.InitialDirectory = ElementConfig.TransferOutPath();
if (ofd.ShowDialog() == DialogResult.OK)
{
FilePath = ofd.FileName.ToString();
ext = FilePath.Substring((FilePath.Length - 3));
if (ext == "xls")
{
MessageBox.Show(FilePath);
AccessImport(FilePath);
}
else if (ext == "mdb")
{
MessageBox.Show(FilePath);
AccessImport(FilePath);
}
}
else
{
System.Windows.Forms.Application.Exit();
}
}
While it isn't advisable to use MessageBoxes to debug your code, I think the immediate problem is that you are doing this in the form's load event.
Try it like this:
protected override void OnShown(EventArgs e) {
base.OnShown(e);
// your code
}
Your problem is definitely the fact that you're trying to do this while loading the Form, because the form isn't yet displayed.
Another alternative would be moving this functionality out of the Load event and give the user a button to push or something like that.
In other words:
private void SubContractedData_Load(object sender, EventArgs e)
{
// unless you're doing something else, you could remove this method
}
Add a button that handles this functionality:
private void SelectDataSourceClick(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Access Databases |*.*|Excel Workbooks|*.xls";
ofd.Title = "Select the data source";
ofd.InitialDirectory = ElementConfig.TransferOutPath();
if (ofd.ShowDialog() == DialogResult.OK)
{
var FilePath = ofd.FileName.ToString();
var ext = Path.GetExtension(FilePath).ToLower();
switch (ext)
{
case ".xls":
MessageBox.Show(FilePath);
AccessImport(FilePath);
break;
case ".mdb":
MessageBox.Show(FilePath);
AccessImport(FilePath);
break;
default:
MessageBox.Show("Extension not recognized " + ext);
break;
}
}
else
{
System.Windows.Forms.Application.Exit();
}
}

Categories