J'essaye de créer un WinForm qui lit un fichier sélectionné et l'affiche dans un TextBox. Mon problème est d'avoir accès à mon objet par d'autres gestionnaires d'événements. Je veux essentiellement que mon nom de fichier soit affiché dans un TextBox après avoir cliqué sur select mais je veux que le contenu du fichier soit placé dans une TextBox séparée après avoir cliqué sur le bouton open. Le nom du fichier s'affiche lorsque je place mon objet à l'intérieur du bouton de sélection, mais je ne peux pas accéder à ce contenu une seconde fois lorsque j'essaie de le placer dans le bouton d'ouverture. Vous pouvez voir toutes mes affaires, je commentais que j'ai essayéC# winforms comment accéder au même objet dans différents gestionnaires d'événements
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 { }
}
}*/
}
}
En outre, vous pouvez changer 'System.IO.File.ReadAllText (openFileDialog1.FileName),' 'à System.IO.File.ReadAllText (displayBox.Text);' –