How to know which button was clicked?

Asked

Viewed 4,607 times

3

I have three buttons, one for insert, another to alter and one for record.

The button of record will work to save data either from an insertion or a change.

How to identify which button I pressed to the button Record whether I am saving an insert or a change?

private void button_inserir_Click(object sender, EventArgs e)
{
    this.Text = "Inserir dados";

    textBox_ordenado.ReadOnly = false;
    textBox_ordenado.Enabled = true;
    textBox_ordenado.Focus();

    textBox_subsidios.ReadOnly = false;
    textBox_subsidios.Enabled = true;
    textBox_subsidios.TabStop = true;

    dateTimePicker_data.Enabled = true;
    button_guardar.Visible = true;
}

private void button_alterar_Click(object sender, EventArgs e)
{
    this.Text = "Alterar dados";

    textBox_ordenado.ReadOnly = false;
    textBox_ordenado.Enabled = true;
    textBox_ordenado.Focus();

    textBox_subsidios.ReadOnly = false;
    textBox_subsidios.Enabled = true;
    textBox_subsidios.TabStop = true;

    dateTimePicker_data.Enabled = true;
    button_guardar.Visible = true;
}

private void button_guardar_Click(object sender, EventArgs e)
{
    if (button_inserir) // Não sei como fazer
    {
        // executa uma stored Procedure (inserir)
    }
    else if (button_alterar) // Não sei como fazer
    {
        // executa outra stored Procedure (alterar)
    }       
}
  • how about? if(this.Text == "Inserir dados") else if(this.Text == "Alterar dados")

  • Got that way @Marconi Thanks so much for the help

  • 1

    Glad I could help you @Diogo.

  • @Marconi Why not put an answer?

  • 1

    @zekk doesn’t even need yours is already well completed.:)

2 answers

2


This will depend on how the button Record is invoked, if you call it so:

private void button_inserir_Click(object sender, EventArgs e)
{
    // ...
    button_guardar_Click(sender, e);
}

You may know who called the button this way:

private void button_guardar_Click(object sender, EventArgs e)
{
   Button btn = sender as Button;
   MessageBox.Show(btn.Name); // button_inserir

   // if (btn.Name == "button_inserir") { }
}

Another way is to use a variable to store a value when one of the buttons is clicked, on the button Keep you check the value of the variable and perform the procedures according to the chosen method.

// 0: Nenhum botão clicado / 1: botão inserir clicado / 2: botão alterar clicado
static int metodoGuardar = 0; 
// ...

private void button_inserir_Click(object sender, EventArgs e)
{
   // Códigos aqui...
   metodoGuardar = 1;
}

private void button_alterar_Click(object sender, EventArgs e)
{
   // Códigos aqui...
   metodoGuardar = 2
}

private void button_guardar_Click(object sender, EventArgs e)
{
   if (metodoGuardar == 1)
   {
      // Botão "inserir" foi clicado
   } else if (metodoGuardar == 2)
   {
      // Botão "alterar" foi clicado
   } else
   {
      // Nenhum dos botões "inserir" e "alterar" foram clicados
   }
}

Related: Retrieve information from the object sender

  • I couldn’t get it that way @zekk ... Nothing happened

  • @Diogosousa I complemented the answer, see if the other way can also be applied in your case.

  • 1

    Thank you @zekk I managed using the variable, I could not calling the button... I think q I have to see better how it works Sender and Eventargs. Thank you very much

1

inserir a descrição da imagem aquiGood night, @Diogo Sousa.

I use constants and through them I check inside the Save or Effective button if it is an INSERT or UPDATE command.

I also use a property that is loaded with the contents of the constant when button is clicked;

Examples:

// Constantes
private const string strConstInseri = "Inseri";
private const string strConstAltera = "Altera";
private const string strConstCancela = "Cancela";
private const string strConstConsulta = "Consulta";
private const string strConstEfetiva = "Efetiva";

// Atributos
private static string strTextBotao;

// Propriedade é utilizada para, manipular a propriedade "Text" dos botões
public static string StrTextBotao
{
    get { return strTextBotao; }
    private set { strTextBotao = value; }
}

// Botão Inseri
private void btnInseri_Click(object sender, EventArgs e)
{
    txtCodInstrucao.Clear();
    txtConteudo.Clear();

    // É setado um valor na propriedade e esse valor será utilizado para distinguir as operações na hora de efetivar no evento click do "botão - Efetiva"
    StrTextBotao = strConstInseri;

    HabDes(StrTextBotao);
}

// Botão Altera
private void btnAltera_Click(object sender, EventArgs e)
{
    if (dgvCodRejeicao.Rows.Count > 0)
    {
        if (dgvCodRejeicao.SelectedRows.Count > 0)
        {
            txtCodInstrucao.Text = dgvCodRejeicao["colCodInstrucao", dgvCodRejeicao.CurrentRow.Index].Value.ToString();
            txtConteudo.Text = dgvCodRejeicao["colConteudo", dgvCodRejeicao.CurrentRow.Index].Value.ToString();

            StrTextBotao = strConstAltera;

            HabDes(StrTextBotao);
        }
    }
    else
    {
        MessageBox.Show("Selecione um registro na tabela para fazer a alteração.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }
}

// Botão Efetiva
private void btnEfetiva_Click(object sender, EventArgs e)
{
    Cursor.Current = Cursors.WaitCursor;

    #region INSERI

    if (StrTextBotao == strConstInseri)
    {
        if (MessageBox.Show("Deseja realmente inserir um novo registro ?", "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
        {
            txtCodInstrucao.Focus();
            return;
        }

        if (ValidaCampos())
        {  
           // Se a validação estiver OK é implementado o código de INSERT
        }
   }
   #endregion

   #region ALTERA

   else if (StrTextBotao == strConstAltera)
   {
        if (MessageBox.Show("Deseja realmente atualizar as informações ?", "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
        {
            txtConteudo.Focus();
            return;
        }

        if (ValidaCampos())
        { 
           // Se a validação estiver OK é implementado o código de ALTERA
        }
   }
   #endregion

   Cursor.Current = Cursors.Default;
}

/// <summary>
/// Método que habilita ou desabilita os campos de acordo com o parâmetro de entrada
/// </summary>
/// <param name="pstrTextBtn"></param>
private void HabDes(string pstrTextBtn)
{
    if (strConstInseri == pstrTextBtn) // Inseri
    {
            txtCodInstrucao.Enabled = true;
            txtConteudo.Enabled = true;
            txtCodInstrucao.Focus();

            btnInseri.Enabled = false;
            btnAltera.Enabled = false;
            btnConsulta.Enabled = false;
            btnCancela.Enabled = true;
            btnEfetiva.Enabled = true;
    }
    else if (strConstCancela == pstrTextBtn) // Cancela
    {
            txtCodInstrucao.Enabled = false;
            txtConteudo.Enabled = false;

            btnInseri.Enabled = true;
            btnAltera.Enabled = true;
            btnConsulta.Enabled = true;
            btnCancela.Enabled = false;
            btnEfetiva.Enabled = false;
    }
    else if (strConstAltera == pstrTextBtn) // Altera
    {
            txtCodInstrucao.Enabled = false;
            txtConteudo.Enabled = true;
            txtConteudo.Focus();

            btnInseri.Enabled = false;
            btnAltera.Enabled = false;
            btnConsulta.Enabled = false;
            btnCancela.Enabled = true;
            btnEfetiva.Enabled = true;
    }
    else if (strConstConsulta == pstrTextBtn) // Consulta
    {
            txtCodInstrucao.Enabled = false;
            txtConteudo.Enabled = false;

            btnInseri.Enabled = true;
            btnAltera.Enabled = true;
            btnConsulta.Enabled = true;
            btnCancela.Enabled = true;
            btnEfetiva.Enabled = false;
    }
    else if (StrTextBotao == pstrTextBtn) // Efetiva
    {
            txtCodInstrucao.Enabled = false;
            txtConteudo.Enabled = false;

            btnInseri.Enabled = true;
            btnAltera.Enabled = true;
            btnConsulta.Enabled = true;
            btnCancela.Enabled = true;
            btnEfetiva.Enabled = false;
    }
}
  • Good evening @Diego Farias I’m trying to test the way you do but I’m a little lost. What is Habdes you use? is that I tried to put and it does not give.

  • @Diogosousa, Hasdes(), is the method that enables or disables form fields. In case you can ignore this method now and think about it after you manage to make it work what you need.

  • @Diogosousa, I edited my answer and added the code of the Habdes() method, so you have the basis of how the above examples work. Within this method I have with components of my form. So enable or disable them according to the button that was clicked.

  • @Diogosousa, I added the image of how the form is for you a better idea of how buttons and methods work.

Browser other questions tagged

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