Add a checkbox column to the datagridview

Asked

Viewed 1,405 times

3

How to add a Checkbox column in Datagridview ?

I need to do this for the user to select the Datagridview line with the Checkbox and then click the Save button.

private void btnRestricao_Click_2(object sender, EventArgs e)
        {
            OleDbDataReader dr = null;
            try
            {
                this.pnlModalMotivo.Visible = true;

                dr = MotivoNegocio.ListarMotivo();

                for (int i = 0; i < dr.FieldCount; i++)
                {
                    DataGridViewColumn coluna = new DataGridViewTextBoxColumn();

                    coluna.HeaderText = dr.GetName(i);
                    coluna.Visible = true;
                    coluna.Name = "coluna" + 1;
                    coluna.Resizable = DataGridViewTriState.True;
                    dgvMotivo.Columns.Add(coluna);
                }

                while (dr.Read())
                {
                    object[] campos = new object[dr.FieldCount];

                    for (int i = 0; i < dr.FieldCount; i++)
                        campos[i] = dr.GetValue(i);

                    dgvMotivo.Rows.Add(campos);
                }

            }
            catch(Exception ex)
            {
                MessageBox.Show("Erro: " + ex.Message);
            }
        }

2 answers

4

It can be done through itself datagridView, Follow the steps:inserir a descrição da imagem aqui

Next screen will appear Edit Columns.

inserir a descrição da imagem aqui

Just select from the TYPE option datagridViewCheckBoxColumn and finally click on Add.

0

To Insert, use Datagridviewcheckboxcolumn:

var col = new DataGridViewCheckBoxColumn();
col.Name = "Coluna" 
col.HeaderText = "Titulo";
col.FalseValue = "0";
col.TrueValue = "1";

//Make the default checked
col.CellTemplate.Value = true;
col.CellTemplate.Style.NullValue = true;

dataGridView1.Columns.Insert(0, col);

To capture values (checked):

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.IsNewRow) continue;

    if (Convert.ToBoolean(row.Cells["Coluna"].FormattedValue))
    {
        // Capture os valores aqui 
    }
}

Browser other questions tagged

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