How to open an Openfiledialog box when selecting a Tabcontrol Tab?

Asked

Viewed 50 times

1

I would like when the user selects a particular Tab, to immediately open an Openfiledialog box.

I already have this Savefiledialog, but it’s in the button click method:

private void btnGuardar_Click(object sender, EventArgs e)
    {
        SaveFileDialog save = new SaveFileDialog();
        save.InitialDirectory = @"C:\Ficheiros\";
        save.Title = "Salvar Ficheiro";
        save.Filter = "txt files (*.txt)|*txt|All files (*.*)|*.*";
        if (save.ShowDialog() == DialogResult.Cancel) return;

        if (save.ShowDialog() == DialogResult.OK)
        {
            StreamWriter escritor;

            if (tabControl1.SelectedTab == tpFicheiro)
            {
                escritor = new StreamWriter(save.FileName, false, Encoding.Default);
                escritor.WriteLine(tbFicheiro1.Text);
            }
            else
            {
                escritor = new StreamWriter(save.FileName, true, Encoding.Default);
                escritor.WriteLine(tbFicheiro2.Text);
            }

            escritor.Flush();
            escritor.Close();
        }
  • Could someone help me with this?

1 answer

3


You can overload 2 Control event TabControl:

  • Selecting -> is triggered when the TabControl is being selected.
  • Selected -> is triggered after selecting the TabControl.

You can find events through the Properties tab. Once the TabControl selected, in the properties tab click on the icon with radius image in the top bar of the tab. Find the action and 2 clicks category in the event corresponding to your need. Rewrite your code in the event method generated by the IDE.

Another way is to write your own method:

private void SelecionandoPagina(object objeto, TabControlCancelEventArgs evento)
{
     //Aqui voçê escreve seu código...
}

private void PaginaSelecionada(object objeto, TabControlEventArgs evento)
{
    //Usei para teste.
     MessageBox.Show($"Pág:{evento.TabPageIndex.ToString()}, Nome:{evento.TabPage.Name}");
}

If you choose the above form don’t forget to overload the Control:

tabControl1.Selecting += new TabControlCancelEventHandler(SelecionandoPagina);

tabControl1.Selected += new TabControlEventHandler(PaginaSelecionada);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.