[c#] How to bind list to dataGridView?

I seem to be running around in circles and have been doing so in the last hours.

I want to populate a datagridview from an array of strings. I've read its not possible directly, and that I need to create a custom type that holds the string as a public property. So I made a class:

public class FileName
    {
        private string _value;

        public FileName(string pValue)
        {
            _value = pValue;
        }

        public string Value
        {
            get 
            {
                return _value;
            }
            set { _value = value; }
        }
    }

this is the container class, and it simply has a property with the value of the string. All I want now is that string to appear in the datagridview, when I bind its datasource to a List.

Also I have this method, BindGrid() which I want to fill the datagridview with. Here it is:

    private void BindGrid()
    {
        gvFilesOnServer.AutoGenerateColumns = false;

        //create the column programatically
        DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn();
        DataGridViewCell cell = new DataGridViewTextBoxCell();
        colFileName.CellTemplate = cell; colFileName.Name = "Value";
        colFileName.HeaderText = "File Name";
        colFileName.ValueType = typeof(FileName);

        //add the column to the datagridview
        gvFilesOnServer.Columns.Add(colFileName);

        //fill the string array
        string[] filelist = GetFileListOnWebServer();

        //try making a List<FileName> from that array
        List<FileName> filenamesList = new List<FileName>(filelist.Length);
        for (int i = 0; i < filelist.Length; i++)
        {
            filenamesList.Add(new FileName(filelist[i].ToString()));
        }

        //try making a bindingsource
        BindingSource bs = new BindingSource();
        bs.DataSource = typeof(FileName);
        foreach (FileName fn in filenamesList)
        {
            bs.Add(fn);
        }
        gvFilesOnServer.DataSource = bs;
    }

Finally, the problem: the string array fills ok, the list is created ok, but I get an empty column in the datagridview. I also tried datasource= list<> directly, instead of = bindingsource, still nothing.

I would really appreciate an advice, this has been driving me crazy.

This question is related to c# .net binding datagridview

The answer is


may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you

public class FileName
{        
     [DisplayName("File Name")] 
     public string FileName {get;set;}
     [DisplayName("Value")] 
     public string Value {get;set;}
}

and then you can bind List as datasource as

private void BindGrid()
{
    var filelist = GetFileListOnWebServer().ToList();    
    gvFilesOnServer.DataSource = filelist.ToArray();
}

for further information you can visit this page Bind List of Class objects as Datasource to DataGridView

hope this will help you.


Instead of create the new Container class you can use a dataTable.

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;

More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString


I know this is old, but this hung me up for awhile. The properties of the object in your list must be actual "properties", not just public members.

public class FileName
{        
     public string ThisFieldWorks {get;set;}
     public string ThisFieldDoesNot;
}

Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:

List<string> filenamesList = ...;
foreach(string filename in filenamesList)
      gvFilesOnServer.Rows.Add(new object[]{filename});

In any case, thanks user927524 for clearing this weird behavior!!


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to binding

Binding ComboBox SelectedItem using MVVM Binding List<T> to DataGridView in WinForm Angularjs Template Default Value if Binding Null / Undefined (With Filter) Bootstrap control with multiple "data-toggle" How does the 'binding' attribute work in JSF? When and how should it be used? WPF Binding to parent DataContext How to get evaluated attributes inside a custom directive How can I use a C++ library from node.js? bind/unbind service example (android) Datagrid binding in WPF

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results