How to access variable from multiple button handlers - c#

In my app, the user can browse and select a text file. I'm saving the path like this:
private void nacitanie_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Otvoriť Textový súbor.";
dialog.Filter = "TXT files|*.txt";
dialog.InitialDirectory = #"C:\";
if (dialog.ShowDialog() == DialogResult.OK)
{
string path = dialog.FileName;
}
}
Then I need to work with that path in other buttons. How can I return the path of the text file from the button handler method?

You should create path outside nacitanie_Click:
class SomeClass
{
private string path;
.....
private void nacitanie_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Otvoriť Textový súbor.";
dialog.Filter = "TXT files|*.txt";
dialog.InitialDirectory = #"C:\";
if (dialog.ShowDialog() == DialogResult.OK)
{
path = dialog.FileName;
}
}
....
}
and the use it in another methods/handlers.

You need to declare a variable outside of the button handler method:
private string path = string.Empty;
private void nacitanie_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Otvoriť Textový súbor.";
dialog.Filter = "TXT files|*.txt";
dialog.InitialDirectory = #"C:\";
if (dialog.ShowDialog() == DialogResult.OK)
{
path = dialog.FileName;
}
}
That way, you'll be able to access the variable from other button handlers.

Related

Need help to rebuild the functions of the buttons, assign variable in c#

I am trying to build a small .pdf -> .txt / searchable .pdf converter, but I am having trouble to assign the first var result to the other buttons
Made myself a "solution" but the code seems too messed and exagerated.
using IronOcr;
using System;
using System.IO;
namespace ocr
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
var Ocr = new IronTesseract(); // nothing to configure
IronOcr.License.LicenseKey = "SOMELICENSEKEY";
using (var Input = new OcrInput())
{
Input.AddPdf(ofd.FileName, "password");
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
richTextBox1.Text = Result.Text;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
var Ocr = new IronTesseract(); // nothing to configure
IronOcr.License.LicenseKey = "SOMELICENSEKEY";
using (var Input = new OcrInput())
{
Input.AddPdf(ofd.FileName, "password");
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
Result.SaveAsTextFile("pdf.txt");
}
}
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
var Ocr = new IronTesseract(); // nothing to configure
IronOcr.License.LicenseKey = "SOMELICENSEKEY";
using (var Input = new OcrInput())
{
Input.AddPdf(ofd.FileName, "password");
var Result = Ocr.Read(Input);
Console.WriteLine(Result.Text);
Result.SaveAsSearchablePdf("pdfpesquisavel.pdf");
}
}
}
}
}
Tried to assign and use the variable "Result" in the others buttons fuctions (button 2 and button 3)
But it didn't worked.

How to use a variable in a different context?

private void browsebtn_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select Song";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
filedialoglbl.Text = fdlg.FileName;
}
}
private void runbtn_Click(object sender, EventArgs e)
{
var Path = fdlg.FileName;
var pi = new System.Diagnostics.ProcessStartInfo(Path)
{
Arguments = Path.GetFileName(Path),
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(Path),
FileName = "C:\\relax.exe",
Verb = "OPEN"
};
System.Diagnostics.Process.Start(pi);
}
}
As you can see I am trying to select a file and use that file to run another program but I don't want to use windows default.
My error is in
var Path = fdlg.FileName;
The problem is fdlg isnt in the same context and i need to use the directory chosen from before, any ideas on how to do this?
From the answers I have tried this:
private OpenFileDialog fdlg = new OpenFileDialog();
private void browsebtn_Click(object sender, EventArgs e)
{
fdlg.Title = "Select Song";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
filedialoglbl.Text = fdlg.FileName;
}
}
private void runbtn_Click(object sender, EventArgs e)
{
var Path = fdlg.Text;
var pi = new System.Diagnostics.ProcessStartInfo(Path)
{
Arguments = Path.GetFileName(Path),
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(Path),
FileName = "C:\\relax.exe",
Verb = "OPEN"
};
System.Diagnostics.Process.Start(pi);
}
and I get an error saying 'OpenFileDialog' doesnt have a definition or extension method for 'Text' and with the line in the class:
private OpenFileDialog fdlg = new OpenFileDialog();
I get a new error saying that 'GetFileName' and 'GetDirectoryName' don't have definitions or extension methods in the 'string'
EDIT
I renamed path to directory but same error
private void runbtn_Click(object sender, EventArgs e)
{
var directory =filedialoglbl.Text;
var pi = new System.Diagnostics.ProcessStartInfo(directory)
{
Arguments = directory.GetFileName(directory),
UseShellExecute = true,
WorkingDirectory = directory.GetDirectoryName(directory),
FileName = "C:\\relax.exe",
Verb = "OPEN"
};
System.Diagnostics.Process.Start(pi);
}
You are using the dialog in your runbtn_Click method only for the FileName. You saved it into a label called filedialoglbl.Text. Use it.
private void browsebtn_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select Song";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
filedialoglbl.Text = fdlg.FileName;
}
}
private void runbtn_Click(object sender, EventArgs e)
{
var path = filedialoglbl.Text;
var pi = new System.Diagnostics.ProcessStartInfo(path)
{
Arguments = Path.GetFileName(path),
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(path),
FileName = "C:\\relax.exe",
Verb = "OPEN"
};
System.Diagnostics.Process.Start(pi);
}
Edit
You can't use Path with uppercase because your are shawoding the Path class and you can't use their methods.
Declare OpenFileDialog fdlg outside of your methods as a class member (field), e.g.
private OpenFileDialog fdlg = new OpenFileDialog();

How to re-use OpenFileDialog method in C# for multiple buttons

Currently I have this code:
private void FirstButton_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Reset();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//some code
}
}
and same code for
private void SecondButton_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Reset();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//some code
}
}
I realized that I need to reuse the OpenFileDialog multiple times, so I'm asking how can I make it to be called multiple times?
I already look into these:
link1,link2
but to no avail. Thank you in advance.
You need to declare the OpenFileDialog outside of either method.
For example, you could make it a field:
protected OpenFileDialog _openFileDialog = new OpenFileDialog();
Then both methods can use it:
// Call this from Form_Load() or some such:
private void InitializeOpenFileDialog()
{
_openFileDialog.InitialDirectory = "c:\\";
_openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
_openFileDialog.FilterIndex = 2;
_openFileDialog.RestoreDirectory = true;
}
private void FirstButton_Click(object sender, EventArgs e)
{
// not needed now: OpenFileDialog openFileDialog1 = new OpenFileDialog();
_openFileDialog.Reset();
if (_openFileDialog.ShowDialog() == DialogResult.OK)
{
//some code
}
}
private void SecondButton_Click(object sender, EventArgs e)
{
// not needed now: OpenFileDialog openFileDialog1 = new OpenFileDialog();
_openFileDialog.Reset();
if (_openFileDialog.ShowDialog() == DialogResult.OK)
{
//some code
}
}
This is what I meant with my comment:
using System;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private System.Windows.Forms.DialogResult dialogFunction()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Reset();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
return (openFileDialog1.ShowDialog());
}
private void button1_Click(object sender, EventArgs e)
{
if (dialogFunction() == System.Windows.Forms.DialogResult.OK)
{
/*do stuff*/
}
}
private void button2_Click(object sender, EventArgs e)
{
if (dialogFunction() == System.Windows.Forms.DialogResult.OK)
{
/*do stuff*/
}
}
}
}
And actually you could just use the very same handler for both clicks
private void OneClickForAll(object sender, EventArgs e)
{
if (dialogFunction() == System.Windows.Forms.DialogResult.OK)
{
/*do stuff*/
}
}
go to properties of each button
and in the events tab
Select the function above (you could even just delete one of the button_Click functions and assign the other if both buttons are doing the very same.
So now you will have something like
private System.Windows.Forms.DialogResult dialogFunction()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Reset();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
return (openFileDialog1.ShowDialog());
}
private void OneClickForAll(object sender, EventArgs e)
{
if (dialogFunction() == System.Windows.Forms.DialogResult.OK)
{
/*do stuff*/
}
}
If you need to do diff stuff on each button if dialogResult == "OK" you could use the name property of every button and use a switch sentence:
if (dialogFunction() == System.Windows.Forms.DialogResult.OK)
{
switch (((Button)sender).Name)
{
case "button1":
/*do stuff for button 1 click*/
MessageBox.Show("you clicked button 1");
break;
case "button2":
/*do stuff for button 1 click*/
MessageBox.Show("you clicked button 2");
break;
default:
break;
}
}

Trying to save file without using SaveFileDialog

I am creating a text editor and i am stuck on the SaveFileDialog window opening
and asking to overwrite the current file open.
I have seen all the similar questions asked like this on SO but none have been able to help me. I have even tried the code from this question: "Saving file without dialog" Saving file without dialog
I got stuck on my program having a problem with FileName.
Here is the code i have currently
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(save.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
}
}
So my question is how can i modify my code so that i can save a file currently open without having the SaveFileDialog box opening everytime?
I do understand that it has something to do with the fact that i'm calling .ShowDialog but i don't know how to modify it.
When opening the file, save the FileName in a form-level variable or property.
Now while saving the file, you can use this FileName instead of getting it from a FileOpenDialog.
First declare a variable to hold filename at form level
// declare at form level
private string FileName = string.Empty;
When opening a file, save the FileName in this variable
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
// save the opened FileName in our variable
this.FileName = open.FileName;
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
And when doing SaveAs operation, update this variable
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
// save the new FileName in our variable
this.FileName = saving.FileName;
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
The save function can then be modified like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.FileName))
{
// call SaveAs
saveAsToolStripMenuItem_Click(sender, e);
} else {
// we already have the filename. we overwrite that file.
StreamWriter writer = new StreamWriter(this.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
In the New (and Close) function, you should clear this variable
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear the FileName
this.FileName = string.Empty;
richTextBox1.Clear();
}
Create a new string variable in your class for example
string filename = string.empty
and then
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(filename)) {
//Show Save filedialog
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
filename = save.FileName;
}
}
StreamWriter writer = new StreamWriter(filename);
writer.Write(richTextBox1.Text);
writer.Close();
}
The SaveFileDialog now only opens if fileName is null or empty
You will have to store the fact that you have already saved the file, e.g. by storing the file name in a member variable of the Form class you have. Then use an if to check whether you have already saved your file or not, and then either display the SaveFileDialog using ShowDialog() (in case you haven't) or don't and continue to save to the already defined file name (stored in your member variable).
Give it a try, do the following:
Define a string member variable, call it _fileName (private string _fileName; in your class)
In your saveToolStripMenuItem_Click method, check if it's null (if (null == _fileName))
If it is null, continue as before (show dialog), and after getting the file name, store it in your member variable
Refactor your file writing code so that you either get the file name from the file dialog (like before), or from your member variable _fileName
Have fun, C# is a great language to program in.
First, extract method from saveAsToolStripMenuItem_Click: what if you want add up a popup menu, speed button? Then just implement
public partial class Form1: Form {
// File name to save text to
private String m_FileName = "";
private Boolean SaveText(Boolean showDialog) {
// If file name is not assigned or dialog explictly required
if (String.IsNullOrEmpty(m_FileName) || showDialog) {
// Wrap IDisposable into using
using (SaveFileDialog dlg = new SaveFileDialog()) {
dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
dlg.Title = "Save File";
dlg.FileName = m_FileName;
if (dlg.ShowDialog() != DialogResult.OK)
return false;
m_FileName = dlg.FileName;
}
}
File.WriteAllText(m_FileName, richTextBox1.Text);
this.Text = Path.GetFileNameWithoutExtension(m_FileName);
return true;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
// SaveAs: always show the dialog
SaveText(true);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
// Save: show the dialog when required only
SaveText(false);
}
...
}

c# Get File Name

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
this.textBox1.Text = result + "";
}
It just returns "OK"
What am I doing wrong? I wish to get the PATH to the file and display it in a text box.
The ShowDialog method returns whether the user pressed OK or Cancel. This is useful information, but the actual filename is stored as a property on the dialog
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
this.textBox1.Text = newOpen.FileName;
}
}
You need to access the filename:
string filename = newOpen.FileName;
or filenames, if you allowed multiple file selection:
newOpen.FileNames;
Ref.: OpenFileDialog Class
private void button1_Click(object sender, System.EventArgs e) {
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file. Error: " + ex.Message);
}
}
}
You need to read the FileName property of the OpenFileDialog instance. This will get you the path of the selected file.
Here is an example of using an existing file as a default, and getting a new file back:
private string open(string oldFile)
{
OpenFileDialog newOpen = new OpenFileDialog();
if (!string.IsNullOrEmpty(oldFile))
{
newOpen.InitialDirectory = Path.GetDirectoryName(oldFile);
newOpen.FileName = Path.GetFileName(oldFile);
}
newOpen.Filter = "eXtensible Markup Language File (*.xml) |*.xml"; //Optional filter
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
return newOpen.FileName;
}
return string.Empty;
}
Path.GetDirectoryName(file) : Return path
Path.GetFileName(file) : Return filename

Categories

Resources