Pass path from form on button click - c#

I am using this code to generate the path of a selected file:
private void LoadNewFile()
{
OpenFileDialog ofd = new OpenFileDialog();
string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
userSelectedFilePath = ofd.FileName;
}
}
private void tbFilePath_TextChanged(object sender, EventArgs e)
{
}
Before i used this code to pass the data:
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(#"C:\Users", Encoding.UTF8);
How do i modify it that instead of x1 that takes the path manually, i need it to be equal to xmlPath1 , so string x1 = xmlPath1

Just change _xmlPath1 to a field and you can access it from any method within your class.
Example:
public class MyClass
{
protected String _xmlPath1;
' insert your methods here
}
If your methods are not in the same class you have to widen the scope of _xmlPath1 even more.
EDIT: Changed VB.net syntax to C#

1 )If userSelectedFilePath is a private field you can use it in btn_compare_Click
2 )If it is a local variable ,make it a private field and then see 1
3)Make the the method return the file
private string LoadNewFile()
{
OpenFileDialog ofd = new OpenFileDialog();
string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
return ofd.FileName;
else
return null;
}
and use it (you must add validation logic)
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(LoadNewFile(), Encoding.UTF8);
}
Option 3 is the best way so you can avoid the extra field and make btn_compare_Click independent from the rest of the code.
In that case you should also give it a better name like GetFileToRead()

Related

Refactor browse file methods to one method

I have several browse methods for parameters which only differ in which setting and which textbox is used. Can I create a lambda or generic method or something to have only one implementation in C#?
private void buttonBrowseSrcXML_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
try
{
fileDialog.InitialDirectory = Path.GetDirectoryName(Settings.Default.XML_Original_File);
}
catch (ArgumentException) { }
if (fileDialog.ShowDialog() == DialogResult.OK)
{
Settings.Default.XML_Original_File = fileDialog.FileName;
Settings.Default.Save();
textBoxSrcXML.Text = fileDialog.FileName;
}
}
yes, you can move this code into a common method and then pass the setting and textbox to this method and call in each of your methods like the one below.
BrowseFile("XML_Original_File", textBoxSrcXML);
you will need to use these values accordingly in this method.
the method's signature should be something like private void BrowseFile(string settingName, TextBox textbox)
The trick was the [] for settings indexing
private void BrowseForStringSettingsFile(System.Windows.Forms.TextBox textBox, string settingKey) {
OpenFileDialog fileDialog = new OpenFileDialog();
try {
fileDialog.InitialDirectory = Path.GetDirectoryName((string) Settings.Default[settingKey]);
} catch (ArgumentException) { }
if (fileDialog.ShowDialog() == DialogResult.OK) {
Settings.Default[settingKey] = fileDialog.FileName;
Settings.Default.Save();
textBox.Text = fileDialog.FileName;
}
}

How do i read already opened file in a another button click event directly .(i.e without open file dialogue in button click)

void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
var geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
}
How to read files in button1 click directly?
what you want is that your geometry object be accessible in additional scopes besides OpenPolyFile(). So you can simply make the geometry declaration accessible to both methods, declaring it, say, in the form code behind
// class scoped variables
[ThePolyFileType] (pick the right one here :) geometry = null;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
if (geometry != null)
{
//do your stuff
}
}
How do i read already opened file in a another button click event
directly .(i.e without open file dialogue in button click)
I'm not quite sure why you want to read it twice, but if that requirement says, make selected filename available globally and use it.
private string filename;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
filename = ofd.FileName
}
}
Now you have opened filename available in button_clcik you can use this file and read again.
private void button1_Click(object sender, EventArgs e)
{
// now you can read the file.
//File.ReadAllText(filename); //OR
TriangleNet.IO.FileReader.ReadPolyFile(file);
}

Choose file C# and get directory

I'm trying to open a file dialog box so the user can choose the location of an access database. Can someone explain how to add a file dialog when a button is clicked and also how to transform the user choice into a string that contains the file directory ( c:\abc\dfg\1234.txt)?
Thanks
As you did not state the technology you use (WPF or WinForms), I assume you use WinForms. In that case, use an OpenFileDialog in your code. After the dialog was closed, you can get the selected full file name using the FileName property.
There is the following example of how to use it on the documentation page I linked above, which I modified slightly as you want the file name, not the stream:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "Database files (*.mdb, *.accdb)|*.mdb;*.accdb" ;
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string selectedFileName = openFileDialog1.FileName;
//...
}
}
Based on your previous question I assume you are using WinForms.
You can use the OpenFileDialog Class for this purpose. See the code below which will run on your button Click event assuming your button id is button1:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Access files (*.accdb)|*.accdb|Old Access files (*.mdb)|*.mdb";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
}
More information.
Assuming that you actually have a form with button (button1)...
At the constructor hook into button1's click event
...
button1.Click += button1_Click;
...
Then define the handling function and use System.Windows.Forms.OpenFileDialog as you like.
void button1_Click(object sender, EventArgs e)
{
string oSelectedFile = "";
System.Windows.Forms.OpenFileDialog oDlg = new System.Windows.Forms.OpenFileDialog();
if (System.Windows.Forms.DialogResult.OK == oDlg.ShowDialog())
{
oSelectedFile = oDlg.FileName;
// Do whatever you want with oSelectedFile
}
}
It's actually fairly simple
namespace YourProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path = "";
//Declare the File Dialog
OpenFileDialog ofd = new OpenFileDialog();
private void button1_click(object sender, EventArgs e)
{
if (odf.ShowDialog() == DialogResult.OK)
{
path = ofd.FileName;
}
}
}
}

c# Filedialog problems

I have a question about the opfiledialog function within c#. When i dont select a file with openfiledialog it put's a text automaticly in my textbox. That text will be "filedialog1". What can i do to fix this.
using System;
using System.Windows.Forms;
using System.IO;
namespace Flashloader
{
public partial class NewApplication : Form
{
private toepassinginifile _toepassinginifile;
private controllerinifile _controllerinifile;
//private controllerinifile _controlIniFile;
public NewApplication(toepassinginifile iniFile)
{
_controllerinifile = new controllerinifile();
_toepassinginifile = iniFile;
InitializeComponent();
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
public bool Run()
{
var result = ShowDialog();
return result == System.Windows.Forms.DialogResult.OK;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
}
private void button3_Click(object sender, EventArgs e)
{
Toepassing toepassing = new Toepassing();
toepassing.Name = nameBox.Text;
toepassing.Controller = (Flashloader.Controller)controllerComboBox.SelectedItem;
toepassing.TabTip = descBox.Text;
toepassing.Lastfile = openFileDialog1.FileName;
fileBox.Text = openFileDialog1.FileName;
if (nameBox.Text == "")
MessageBox.Show("You haven't assigned a Name");
else if (controllerComboBox.Text == "")
MessageBox.Show("You haven't assigned a Controller");
else if (descBox.Text == "")
MessageBox.Show("You haven't assigned a Desciption");
else if (fileBox.Text == "")
MessageBox.Show("You haven't assigned a Applicationfile");
_toepassinginifile.ToePassingen.Add(toepassing);
_toepassinginifile.Save(toepassing);
MessageBox.Show("Save Succesfull");
DialogResult = DialogResult.OK;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
var newcontroller = new Newcontroller(_controllerinifile);
newcontroller.ShowDialog();
controllerComboBox.DataSource = null;
controllerComboBox.DataSource = _controllerinifile.Controllers;
}
}
}
Thanks all for the help
private void button3_Click(object sender, EventArgs e)
{
toepassing.Lastfile = openFileDialog1.FileName;// Dont do this
fileBox.Text = openFileDialog1.FileName; //or this
Its unclear to me why you are holding onto an Open file dialog I would personally do the following
using(OpenFileDialog ofd = new OpenFileDialog())
{
if(ofd.ShowDialog() == DialogResult.OK)
{
classStringVariable = ofd.FileName;
fileBox.Text = ofd.FileName;
}
}
Then in button 3
toepassing.LastFile = classStringVariable ;
fileBox.Text = classStringVariable ;
When you use the Form Designer to add an OpenFileDialog control on you form, the designer assigns at the property FileName the value openFileDialog1.
I suppose you have set something as the initial value for the property FileName. Then in button_click3 you have no mean to check for the DialogResult and thus you get inconditionally this default back.
Fix it removing this default from the designer FileName property
Just add openFileDialog1.FileName= ""; before you show the dialog.
openFileDialog1.Filter = "Srec Files (.a20; .a21; .a26; .a44)|*.a20; *.a21; *.a26; *.a44|All files (*.*)|*.*";
openFileDialog1.Title = ("Choose a file");
openFileDialog1.InitialDirectory = Path.Combine(Directory.GetCurrentDirectory());
openFileDialog1.RestoreDirectory = true;
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK && openFileDialog1.FileName != "")
{
fileBox.Text = (System.IO.Path.GetFileName(openFileDialog1.FileName));
}
In your button3_Click event you're checking for an empty string file name anyways, so they would get the correct error message and they wouldn't have some weird arbitrary default name show up when they open the dialog.

Can I Use Variables from One Method to another?

Can I use a declared variable or a instance of an object from one method to another?
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
string path = null;
path = OpenFile();
}
private string OpenFile()
{
string path = null;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Open source file";
fileDialog.InitialDirectory = "c:\\";
fileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fileDialog.FilterIndex = 2;
fileDialog.RestoreDirectory = true;
Nullable<bool> result = fileDialog.ShowDialog();
if (result == true)
{
path = fileDialog.FileName;
}
textBox1.Text = path;
return path;
}
Now, I want to get that path and write it on excel. how will I do this, please help, I am week old in using C#.
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "sample.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
string path = null;
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
reportGeneratorVM.ReportGenerator(filename, functionName, path);
}
Thanks
Use an instance field to store the value of your variable.
Like so:
public class MyClass
{
// New instance field
private string _path = null;
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
// Notice the use of the instance field
_path = OpenFile();
}
// OpenFile implementation here...
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "st_NodataSet.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
// Reuse the instance field here
reportGeneratorVM.ReportGenerator(filename, functionName, _path);
}
}
Here is a link which describes fields in much more detail than what I could.
Move the string path as a member inside your class, and remove the declaration inside the methods. that should do it
Use string path as a class level variable.
Use static private string path if you want to use it between pages.
Use private string path if you only need to use it on the current page.
you must define the variable as field in your class:
Private string path = null;
use static private string path;

Categories