Reputation: 23
I'm trying create a WinForm that reads a selected file and displays it into a TextBox. My issue is having my object be accessed by other event handlers. I basically want my file name to be displayed in a TextBox after clicking select but i want the file content to go into a separate TextBox after clicking the open button. The file name is displayed when I put my object inside of the select button but I can't access that content a second time when I try to put it into the open button. You can see all my stuff I commented out that I tried
public partial class xmlForm : Form
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
public xmlForm()
{
InitializeComponent();
}
public void btnSelect_Click(object sender, System.EventArgs e)
{
// Displays an OpenFileDialog so the user can select a Cursor.
// OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "XML files|*.xml";
openFileDialog1.Title = "Select a XML File";
// Show the Dialog.
// If the user clicked OK in the dialog and
// a .xml file was selected, open it.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
displayBox.Text = openFileDialog1.FileName;
var onlyFileName = System.IO.Path.GetFileName(openFileDialog1.FileName);
displayBox.Text = onlyFileName;
/* Button btn = sender as Button;
if (btn != null)
{
if (btn == opnButton)
{
string s = System.IO.File.ReadAllText(openFileDialog1.FileName);
fileBox.Text = s;
}
}*/
/* if (opnButtonWasClicked)
{
string s = System.IO.File.ReadAllText(openFileDialog1.FileName);
fileBox.Text = s;
opnButtonWasClicked = false;
} */
}
/*string s = System.IO.File.ReadAllText(openFileDialog1.FileName);
fileBox.Text = s; */
}
public void opnButton_Click(object sender, EventArgs e)
{
string s = System.IO.File.ReadAllText(openFileDialog1.FileName);
fileBox.Text = s;
/*if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Button btn = sender as Button;
if (btn != null)
{
if (btn == opnButton)
{
string s = System.IO.File.ReadAllText(openFileDialog1.FileName);
fileBox.Text = s;
}
else { }
}
}*/
}
}
Upvotes: 2
Views: 222
Reputation: 3584
Since you have already opened the FileDialog inside the btnSelect_Click handler; Thus you cannot open the already opened Dialog before closing this. So in order to open the dialog again you have to close it before. And then you could have used the statements below:
string s=System.IO.File.ReadAllText(openFileDialog1.FileName);
fileBox.Text = s;
But In your case, To serve the purpose you don't need to open the dialog again after closing. So, just pass the displayBox.Text as parameter of the ReadAllText method inside opnButton_Click handler as the textfield already containing the file name.
string System.IO.File.ReadAllText(displayBox.Text);
fileBox.Text = s;
Thanks
Upvotes: 2