Double click on a Datagridview line transports the data to a form

Asked

Viewed 3,895 times

4

Good morning to all.

Next staff, I have a (query) form that contains the Datagrideview. And the registration form in another form.

I would like to understand, how can I double click on a line of Datagrideview he send all the data from the line to this registration form (so I can crud to change).

Image to illustrate:

inserir a descrição da imagem aqui

Datagrid class

 class datagride
{
    banco conexao = new banco();

    // Atributos

    private string nomeTabela;
    private DataGridView nomeDataGride;

    // Construtor

    public datagride(string pnt, DataGridView pndg)
    {
        nomeTabela = pnt;
        nomeDataGride = pndg;
    }

    public datagride(DataGridView pndg)
    {
        nomeDataGride = pndg;
    }


    // Método

    public DataGridView carregarGride(string sql = "")
    {

        DataSet ds = new DataSet();
        DataTable dt = new DataTable(); //Nova tabela

        ds.Tables.Add(dt);

        NpgsqlDataAdapter da = new NpgsqlDataAdapter();

        if (sql == "")
        {
            sql = "select * from " + nomeTabela;
        }

        da = new NpgsqlDataAdapter(sql, conexao.conecta());
        da.Fill(dt);

        nomeDataGride.DataSource = dt.DefaultView;

        conexao.desconecta();
        return nomeDataGride;
    }

**Builder **

public cliente(cliente c, string pn, string pe, int pt, string pem, string ps, int pcod)
    {
        nome = pn;
        endereco = pe;
        telefone = pt;
        email = pem;
        sexo = ps;
        cod = pcod;
    }

Instance in the form

 private void btnAtualizar_Click(object sender, EventArgs e)
    {
        if (txtCodC.Text == "")
        {
            MessageBox.Show("Digite o código do cliente");
            txtCodC.Focus();
        }
        else
        {
            try
            {
                cliente cli = new cliente(txtNomeCliente.Text, txtEnderecoCliente.Text, Convert.ToInt32(txtTelefoneCliente.Text), txtEmailCliente.Text, cmbSexoCliente.Text, Convert.ToInt32(txtCodC.Text));
                cli.AlterarCliente();
                MessageBox.Show("Alterado com sucesso!");

            }
            catch (Exception ex) // Caso de erro, irá mostrar a mensagem de erro!
            {
                MessageBox.Show(ex.ToString()); // mensagem de erro
            }

        }
    }
  • Man, this print is awful :p

  • I tried to improve @jbueno :)

  • It’s much better. I’m writing an answer. It would help me a lot if you put the code you use to popular Datagrid

  • Okay, I’ve updated @jbueno

  • Take a look at my answer. I tried to be as generic as possible, because without knowing your model is very complicated.

3 answers

4

There are several ways to do this. It depends a lot on your preference/need and some other factors like DataSource of DataGridView.

First, your Form to edit client must be able to receive a parameter of type Cliente in your constructor. Thus, you only need to take the trouble of instantiating an object Cliente, send to the Form and within the Form you define which fields you will show, etc. Let’s assume that the Form be called FormEditarCliente. The builder would look like this:

public FormEditarCliente(Cliente c){ ... }

I’ll show you two ways you can do this

The first (and the one I use most) only works when your DataGridView is populated by a List<T>. Supposing List<Cliente> _clientes is the data source of your grid.

The event CellDoubleClick would look like this:

public static void dataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
     int idCliente = Convert.ToInt32(dataGrid["nomeDaColunaId", e.RowIndex].Value);
     var cliente = _clientes.Single(x => x.Id == idCliente);

     var form = new FormEditarCliente(cliente);
     form.ShowDialog();
}

What is done up there is very simple. The first line takes the Id of the client that is in the DataGridView (I’m guessing the records have an ID and that this ID is a primary key), then a query is made in the list that serves as the data source of DataGridView. This query consists of searching for a record where the Id matches the Id that was captured from DataGridView. So it’s called the Form passing by parameter the client that was selected with Single().

The second (and the one I would use in your case after seeing the edit) consists of just getting the Id of the client that is in the DataGridView and after that search this client in the database. Then pass it by parameter to the Form editing, exactly as it was done before.

public static void dataGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
     int idCliente = Convert.ToInt32(dataGrid["nomeDaColunaId", e.RowIndex].Value);
     Cliente cliente = BuscarClientePorId(idCliente);

     var form = new FormEditarCliente(cliente);
     form.ShowDialog();
}
  • Take a look at my mod builder code and the instance in the form, I got a little lost in that part

  • Lost in what? Have any doubts?

  • So, let’s go in parts... You can join the chat?

  • Yes, I passed the parameter (client c) but qnd do the instance in the form what I will pass in?

  • Yes, I can @jbueno

1

I consider the datagrid and the editing buttons and methods in the same form. So when an Insert, Update or Delete occurs, call the Select method to reload the datagrid.

1

inserir a descrição da imagem aqui

Well you can use Datagridview’s Cellcontentdoubleclick event, in the click you take the index of the line by the clicked cell:

dtClientesDtgv is the name of my Datagrid.

var pegarIndex = dtClientesDtgv.CurrentCell.RowIndex;

And then you can pick up the values of the line through the Index found in Click:

var pegarId = dtClientesDtgv.Rows[pegarIndex].Cells[1].Value.ToString();

From here just pass the values of each cell to its variables.

Browser other questions tagged

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