gpt4 book ai didi

C# winforms如何在不同的事件处理程序中访问同一个对象

转载 作者:太空宇宙 更新时间:2023-11-03 12:22:04 25 4
gpt4 key购买 nike

我正在尝试创建一个 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 作为 readAllText 方法的参数传递给 opnButton_Click 处理程序,因为文本字段已经包含文件名。

string System.IO.File.ReadAllText(displayBox.Text);
fileBox.Text = s;

谢谢

关于C# winforms如何在不同的事件处理程序中访问同一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46750795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com