Add a checkbox column in the datagridview

2

How to add a CheckBox type column in DataGridView?

I need to do this for the user to select the row of the DataGridView 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);
            }
        }
    
asked by anonymous 13.02.2018 / 16:46

2 answers

2

Can be done through datagridView itself, follow the steps:

Then the following screen will appear Edit Columns.

Just select TYPE datagridViewCheckBoxColumn and finally click Add.

    
15.02.2018 / 15:38
0

To Insert, use the 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 (checked):

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

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