I would like to create application in which I could create file, write something into it by button clicking and then close this file by clicking another button. The problem is that when I've declared Streamwrtier object within one button I couldn't invoke file close method from within second button because I've got such error: the name 'file' does not exist in the current context. When I initiate Streamwriter outside the button method problem dissapeares but then file is being created before I will click button. Do you know how could I overcome this issue?
public void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
StreamWriter file = new StreamWriter("test.txt");
file.WriteLine(value.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = true;
button2.Visible = false;
file.Close();
}
Here's the basic fix:
private StreamWriter file = null;
public void button1_Click(object sender, EventArgs e)
{
button1.Visible = false;
button2.Visible = true;
if (file == null)
file = new StreamWriter("test.txt");
file.WriteLine(value.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
button1.Visible = true;
button2.Visible = false;
if (file is object)
file.Close();
}
But really, it's poor practice in most cases to hold the file open. You generally want something more like this, which handles opening and closing the necessary streams all in one go, and only keeps the file open for the minimum necessary duration:
public void button1_Click(object sender, EventArgs e)
{
File.AppendAllText("test.txt", value.ToString());
}
And since we always close the file right away, the second button isn't needed at all.
Related
I'm trying to modify a simple application which use the WebBrowser item:
private void button1_Click(object sender, EventArgs e)
{
var menu = webBrowser1.Document.GetElementById("SomeItem").InvokeMember("click");
webBrowser1.Visible = true;
button1.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Visible = false;
webBrowser1.AllowNavigation = true;
webBrowser1.Navigate("domain");
}
This works fine, the page load and then after clicking the button the user is redirected to the desired location.
Now I'm trying to make this without the help of the button.
Simply put the button code inside the load function didn't help, so I've introduced in my code the DocumentCompleted event.
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowNavigation = true;
webBrowser1.Navigate("SomeDomain");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentComplete);
}
private void wb_DocumentComplete(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
wb.Document.GetElementById("SomeItem").InvokeMember("click");
}
By debugging it, I saw that the wb object is correctly instantiated with the "domain" but I got System.NullReferenceException when I try to retrieve SomeItem.
The document is not fully loaded because I'm still in the load function ?
I am trying to create a application with multiple forms,
I have placed the forms on top of each other in the section needed.
However, the code as provided does not work.
private void home_butt_Click(object sender, EventArgs e)
{
Home_Panel.Visible = true;
Home_Panel.BringToFront();
}
private void Intro_butt_Click(object sender, EventArgs e)
{
Introduction.Visible = true;
Introduction.BringToFront();
Home_Panel.Visible = false;
Crime.Visible = false;
}
private void Crime_butt_Click(object sender, EventArgs e)
{
Crime.Visible = true;
Crime.BringToFront();
Home_Panel.Visible = false;
Introduction.Visible = false;
}
It will the home_Panel on start up but when you click on a button it will only show the Crimes Panel.
Any help will be appreciated.
Why not use the show and hide methods for forms instead of bringing them to the front and setting the visibility? E.G.
private void home_butt_Click(object sender, EventArgs e)
{
Home_Panel.Show();
Crime.Hide();
Introduction.Hide();
}
And vice versa for the other button events?
I'm having trouble loading a file into a RichText control.
First, there are no events in the designer to accomodate drag/drop, so I put these handlers in the form initialization.
Second, the DragEnter() event does not seem to identify text files properly, so dropping is disabled in the RichText (it works fine for a ListBox).
Third, if I get the RT to load the file, it displays an icon/filename inside the RT text area. I cant find any references to this behavior, and can't turn it off.
This code does NOT work:
public Form1()
{
InitializeComponent();
RT.AllowDrop = true;
RT.DragEnter += new System.Windows.Forms.DragEventHandler(RT_DragEnter);
RT.DragDrop += new System.Windows.Forms.DragEventHandler(RT_DragDrop);
}
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// when a text file is dragged to this control, GetDataPresent() returns FALSE.
// this seems to be regardless of the file extension. File is ASCII text only.
// this code DOES work if the underlying control is a ListBox.
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
// when the file is loaded, the RT also displays an icon for the file,
// with the filename, inside the text area ... ?
RT.LoadFile(filenames[0],RichTextBoxStreamType.PlainText);
}
}
In order to get the RT to load a dropped file properly, I use a timer to load the RT outside of the
DragDrop() event:
public string FileToLoad;
private void RT_DragEnter(object sender, System.Windows.Forms.DragEventArgs e) {
// allow anything:
//if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Move;
//else
//e.Effect = DragDropEffects.None;
}
private void RT_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) {
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop, false);
if (null != filenames){
FileToLoad = filenames[0];
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
if (FileToLoad.Length > 0)
{
RT.LoadFile(FileToLoad, RichTextBoxStreamType.PlainText);
FileToLoad = "";
}
}
The latter has the RichText loading the file properly, but this seems like a long way around the block to get LoadFile() to work as expected. Am I doing something wrong?
I've started to learn about System.IO in C# and I want to achieve something like this:
I have two buttons and one TextBox.
The first button event is supposed to use FolderBrowserDialog and let me choose a specific a folder.Then, to save its path in a variable.
The text box is supposed to get as a value the number of folders that I want to create in the choosen path.
The second button is going to create the number of folders(with different name each) written in the textbox at the first button specified path.
My buttons and textbox events so far:
...
int value;
String path;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(fbd.SelectedPath);
path = folderBrowserDialog1.SelectedPath;//store selected path to variable "path"
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (!Directory.Exists(path))//if selected path exists
{
for(int i=0;i<value;i++)//trying to go through as folders as I wrote in the TextBox
{
Directory.CreateDirectory(path + "something");//is something wrong here, I guess.
}
}
}
My questions so far:
what's wrong with my code ?
how can I create each time the for(){} executes a folder with different name ?
I would appreciate any help
int value;
string path = null;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(fbd.SelectedPath);
path = fbd.SelectedPath; //fbd not folderBrowserDialog1
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (path != null && Directory.Exists(path))
for(int i=0;i<value;i++)
Directory.CreateDirectory(Path.Combine(path,string.Format("SomeFolder{0}",i)));
}
I am trying to put together a form application to browse and play WAV files. Currently, it has two buttons - one to browse and select the WAV, the other one is to play. I have implemented the browse button and it is working ok. I checked it by playing the WAV sound within the button, as you can see:
private void Browse_Click(object sender, EventArgs e) {
OpenFileDialog tarik = new OpenFileDialog();
tarik.Title = "Browse...";
tarik.InitialDirectory = #"Desktop";
tarik.Filter = "Wav files (*.wav)|*.wav";
tarik.RestoreDirectory = true;
if (tarik.ShowDialog() == DialogResult.OK) {
textBox1.Text = tarik.FileName;
Stream tarik2 = tarik.OpenFile();
SoundPlayer snd = new SoundPlayer(tarik2);
snd.Play();
}
}
I tested the code and it is working, but when I try to call the 'tarik' from another button:
private void Play_Click(object sender, EventArgs e) {}
As shown above, it says I am not allowed to do this.
The variables that you create in your browse handler are local variables (as they should be) which means they can't be accessed (because they don't exist) once the method ends.
You'll need to create an instance field, which exists for the entire lifetime of the object, to allow the other method to access it:
//new instance field.
private string tarikFileName;
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog tarik = new OpenFileDialog();
tarik.Title = "Browse...";
tarik.InitialDirectory = #"Desktop";
tarik.Filter = "Wav files (*.wav)|*.wav";
tarik.RestoreDirectory = true;
if (tarik.ShowDialog() == DialogResult.OK) {
//store value in instance field
tarikFileName = tarik.FileName;
textBox1.Text = tarik.FileName;
Stream tarik2 = tarik.OpenFile();
using(SoundPlayer snd = new SoundPlayer(tarik2))
snd.Play();
}
}
private void Play_Click(object sender, EventArgs e)
{
if(tarikFileName != null)
{
Stream stream = File.OpenRead(tarikFileName);
using(SoundPlayer snd = new SoundPlayer(stream))
snd.Play();
}
}
Also note that the SoundPlayer should be disposed when you're done with it, so I've wrapped it in a using block to ensure that happens.
I'd suggest the following approach:
Declare the SoundPLayer as a variable of your Form.
In the handler of Browse button get the file name, create a stream and initialize your SoundPlayer with it.
In the handler of Play button call the Play() method of the SoundPlayer.
In order to share data across the two methods you need some place to store the references. In your case I would recommend pulling the file name from textBox1.Text. That way you don't have to worry about managing (opening/closing) the stream in multiple places.
private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog tarik = new OpenFileDialog();
tarik.Title = "Browse...";
tarik.InitialDirectory = #"Desktop";
tarik.Filter = "Wav files (*.wav)|*.wav";
tarik.RestoreDirectory = true;
if (tarik.ShowDialog() == DialogResult.OK) {
textBox1.Text = tarik.FileName;
}
}
private void Play_Click(object sender, EventArgs e)
{
using(Stream tarik2 = File.Open(textBox1.Text, FileMode.Open))
{
SoundPlayer snd = new SoundPlayer(tarik2);
snd.Play();
}
}