Binding List Of String

Many of the components which display data offers us a possibility to bind various types of data to them. In most of the cases there is no problem with this. Almost all of us have bound a collection of string to comboBox just like that.

    List<string> listOfString = new List<string>();
    listOfString.Add("Item 1");
    listOfString.Add("Item number 2");
    listOfString.Add("Item number three");
    myComboBox.DataSource = listOfString;

This displays exactly what we want:

List of string bound to dataGridView.

Unfortunately if we try to do the same with dataGridView:

    myDataGridView.DataSource = listOfString;

Then we get:

List of string bound to dataGridView.

The Reason:

The reason is the binding mechanism which treats string as any other type of object. We didn't specify which property should be bound so the FIRST PUBLIC PROPERTY WAS BOUND.

The Solution:

The first solution which we can find on many pages about programming, is to close the string into a class and bind the list of those objects.

    public class StringContainer
        public string Value { get; set; }

        public StringContainer(string value)
            Value = value;

    List<StringContainer> listOfStringContainer = new List<StringContainer>();

    listOfStringContainer.Add(new StringContainer("Item 1"));
    listOfStringContainer.Add(new StringContainer("Item number 2"));
    listOfStringContainer.Add(new StringContainer("Item number three"));
    myDataGridView.DataSource = listOfStringContainer;

The second solution, which I recommend is to use a DataTable object, which seems to be easier.

    DataTable dt = new DataTable();
    dt.Columns.Add("My first column Name");

    dt.Rows.Add(new object[] { "Item 1" });
    dt.Rows.Add(new object[] { "Item number 2" });
    dt.Rows.Add(new object[] { "Item number three" });

    myDataGridView.DataSource = dt;

The final Result:

List of string bound to dataGridView.

This solution do not require creating new class and gives us the desired effect.