我想創建一個讀取選定文件並將其顯示到文本框中的WinForm。我的問題是讓我的對象被其他事件處理程序訪問。我基本上希望我的文件名在單擊選擇後顯示在文本框中,但我希望文件內容在單擊打開按鈕後進入單獨的文本框。當我將對象放入選擇按鈕時顯示文件名,但當我嘗試將其放入打開按鈕時,我無法再次訪問該內容。你可以看到我所有的東西我註釋掉了,我試圖C#winforms如何在不同的事件處理程序中訪問同一個對象
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 { }
}
}*/
}
}
另外,你可以改變'System.IO.File.ReadAllText(openFileDialog1.FileName);''來System.IO.File.ReadAllText(displayBox.Text);' –