Load string in DataGridView

3

I create a DataGridView with a CheckBox column to be able to mark one or another row.

As data source of the DataGridView I pass a list of strings. When I passed the list, I expected to obtain a datagridview that showed me as the first column, a column of checkbox and the second column the string of the list, but no, instead of the string it shows me its length:

In the Length column you should (or would like to) show the strings passed through the list and not their length.

The way to generate the "Selection" column is as follows:

DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn();
column.HeaderText = "Seleccion";
column.Name = "Seleccion";
column.TrueValue = true;
column.FalseValue = false;
column.IndeterminateValue = false;
column.ThreeState = false;
column.ValueType = typeof(Boolean);

dgRemotas.Columns.Add(column);

and to add the string list I do the following:

dgRemotas.DataSource = list;

list is defined as:

public List<string> list;

How can I show the string instead of its length?

    
asked by Pablo Simon DiEstefano 30.01.2018 в 12:19
source

2 answers

5

By default DataGridView has the property AutoGenerateColumns to true. Having that property activated, the DataGridView tries to obtain the properties of the DataSource objects that you are passing to it. But, it turns out that string only has one property, and this is Length . That's why he shows you that column.

To fix it, the first step is to deactivate AutoGenerateColumns :

dgRemotas.AutoGenerateColumns = false;

Next, you must add the second column that should show the string of your list:

DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
column2.HeaderText = "Texto";
column2.Name = "Texto";
column2.DataPropertyName = "Valor";
dgRemotas.Columns.Add(column2);

Look at DataPropertyName . We must pass in the DataSource a list of objects that have a property that is called Valor , so we do the following:

dgRemotas.DataSource = lista.Select(x => new { Valor = x }).ToList();

In this way, we generate a list of objects with a property called Valor that contains the text to be displayed.

    
answered by 30.01.2018 / 12:54
source
1

By default DataGridView will look at the properties of the container objects in the list. For string there is only one property - length . So, you need a container for a chain, like this:

public class StringValue
{
    public StringValue(string s)
    {
        _value = s;
    }
    public string Value { get { return _value; } set { _value = value; } }
    string _value;
}

Next, you link the object List<StringValue> to the DataGridView .

List<StringValue> list = new List<StringValue>();

//Rellenamos lista
list.Add(new StringValue("texto"));

dgRemotas.DataSource = list;

NOTE: Response obtained from this link .

    
answered by 30.01.2018 в 13:00