Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a List<string> to a DataGridView control?

I have a simple List<string> and I'd like it to be displayed in a DataGridView column.
If the list would contain more complex objects, simply would establish the list as the value of its DataSource property.

But when doing this:

myDataGridView.DataSource = myStringList;

I get a column called Length and the strings' lengths are displayed.

How to display the actual string values from the list in a column?

like image 528
agnieszka Avatar asked Jan 26 '09 10:01

agnieszka


People also ask

Which properties are used to bind a DataGridView control?

Binding Data to the Control. For the DataGrid control to work, it should be bound to a data source using the DataSource and DataMember properties at design time or the SetDataBinding method at run time.

How to DataGridView in c# Windows application?

Drag and drop DataGridView control from toolbox to form window. Figure 2. Now choose a data source by right clicking on the DataGridView and then click on Add Project Data Source. We will be adding a new data source to the project right now.


3 Answers

Try this:

IList<String> list_string= new List<String>();
DataGridView.DataSource = list_string.Select(x => new { Value = x }).ToList();
dgvSelectedNode.Show();

I hope this helps.

like image 62
Tamanna Jain Avatar answered Oct 18 '22 17:10

Tamanna Jain


Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this

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

Then bind List<StringValue> object to your grid. It works

like image 41
sinm Avatar answered Oct 18 '22 17:10

sinm


The following should work as long as you're bound to anything that implements IEnumerable<string>. It will bind the column directly to the string itself, rather than to a Property Path of that string object.

<sdk:DataGridTextColumn Binding="{Binding}" />
like image 38
jamisonLikeCode Avatar answered Oct 18 '22 17:10

jamisonLikeCode