I load a DataGridView via a list.
datagridview.DataSource = listaVariables;
This DatagridView is made up of a column (the first) that is of the DataGridViewCheckBoxCell type.
What I want to do is that, depending on a property of the list variables, it is activated as checked or not.
I have tried to do this:
datagridview.Rows[pos].Cell[0].Value = true; //pos es un entero que utilizo para recorrer las filas y pongo 0 en Cell porque es la primera columna la que tiene los CheckBox
and it does nothing, it leaves it unchecked.
I have also tried to create a cell of type DataGridViewCheckBoxCell by setting it to true but it doesn't work either, it gives me a cell format error (System.FormatException: The formatted value of the cell has a wrong type):
DataGridViewCheckBoxCell dC = new DataGridViewCheckBoxCell(true);
datagridview.Rows[pos].Cell[0] = dC;
In this last test, I believe that the cell that I create (although it does not let me assign it) that would not set the checkbox that contains it to true either.
I have also tried to do:
dataGridView.Rows[pos].SetValues(true); //Se supone que la primera celda de la fila la debería poner a true y no lo hace
Y
var values = new bool[] { true };
dataGridView.Rows[pos].SetValues(values);
and I continue with the same result, it does not show me the activated checkbox.
The list with which I load the datagrid I define it like this:
List<PlacaVariableP> listaVariables;
The Variable object is as follows:
public class PlacaVariableP:IComparable
{
public virtual long id_placavariable { get; set; }
public virtual long idplaca { get; set; }
public virtual string descripcion { get; set; }
public virtual string unidades { get; set; }
public virtual string idFichero { get; set; }
public virtual int CompareTo(object obj)
{
PlacaVariableP c = (PlacaVariableP)obj;
return String.Compare(this.descripcion, c.descripcion, StringComparison.Ordinal);
}
public virtual void toString(object obj)
{
obj.ToString();
}
}
The problem is that when working with a DataGridView you have two ways to do it:
In this way you set the content to display in the DataGridView through the DataSource property and this is the information that is displayed.
If you want to make changes you must make them in the object that you have established as DataSource and re-associate it. You cannot modify the content of cells directly.
You can fill the content by adding DataGridViewRow objects to the DataGridView's Rows collection and setting the values for each cell.
This way you can manipulate the content of the cells directly.
Therefore, if you are going to use a DataSource, the elements contained in the list that you associate to the DataSource should have a property to set the value of the column of type check.
You could do something like this:
In this way the elements of the DataSource will have a property (in the example
columnaCheck
) with the value for the column.You could use DataGridViewCheckBoxColumn. A simple example would be: