我正在尝试创建一个 WinForm 来读取选定的文件并将其显示到文本框中。我的问题是让其他事件处理程序访问我的对象。我基本上希望在单击选择后将文件名显示在文本框中,但我希望在单击打开按钮后将文件内容显示在单独的文本框中。当我将对象放入选择按钮内时,会显示文件名,但当我尝试将其放入打开按钮时,我无法再次访问该内容。你可以看到我注释掉的所有我尝试过的东西
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 { }
}
}*/
}
}
最佳答案
由于您已经在 btnSelect_Click 处理程序中打开了 FileDialog;因此,在关闭对话框之前,您无法打开已打开的对话框。因此,为了再次打开该对话框,您必须先将其关闭。然后您可以使用以下语句:
string s=System.IO.File.ReadAllText(openFileDialog1.FileName);
fileBox.Text = s;
但就您而言,为了达到目的,您不需要在关闭后再次打开对话框。因此,只需将 displayBox.Text 作为 opnButton_Click 处理程序内 ReadAllText 方法的参数传递,因为文本字段已包含文件名。
string System.IO.File.ReadAllText(displayBox.Text);
fileBox.Text = s;
谢谢
关于C# winforms如何在不同的事件处理程序中访问同一对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46750795/