Reputation: 413
In my windows application I am using MS access database. In mainForm (Contain menu), where user will select (open) data file through Dialogbox. And he will be able to select a menu to access the other forms.
Here I need to store the datafile name in a variable and use the same datafile name in the connection string to get the data from the selected data file.
How can I pass the selected database file name through one form to another.
In form 1, I declare a variable;
public string dtFile;
I stored the file path in the dtfile
variable at Open file Dialog.
dtFile = openFileDialog.FileName;
In the form2 I have written
Form1 frm = new Form1;
string strDataFile = frm.dtFile;
Here I am getting null value. How to get the data of dtFile variable of Form 1 in From 2
Upvotes: 0
Views: 437
Reputation: 413
In First form declare dtFileName
as static variable.
public static string dtFileName;
On selecting file name through dialogbox
dtFileName = openFileDialog.FileName;
And in form2
public partial class Form2 : Form
{
string strDataFilePath = "";
public Form2 ()
{
InitializeComponent();
strDataFilePath = Form1.dtFileName.ToString();
}
}
Upvotes: 0
Reputation: 62488
you can do like this, you will be able to access all the things of Form1 on the other form:
private void button1_Click(object sender, EventArgs e)
{
Form1 newform = new Form1();
newform = this;
this.Hide();
MySecform = new Form2(ref newform);
MySecform.Show();
}
The other way around is using custom Events:
see details here:
http://www.codeproject.com/Articles/17371/Passing-Data-between-Windows-Forms
you can also make a Static Class if you want the value to be accessible in all forms of your application:
static class Global
{
private static string _globalVar = "";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
}
Upvotes: 1