Bind list to gridview C#

22,400

Solution 1

I managed to solve this problem. I did it this way, maybe it will help someone. You can use DataTable and then bind DT to gridview.

DataTable dt = new DataTable();
dt.Columns.Add("values");

foreach(string items in description)
{
    DataRow row = dt.NewRow();
    dt.Rows.Add(items);
}
this.dataGridView2.DataSource = dt;

Solution 2

this.dataGridView1.DataSource = new BindingSource(list);

Share:
22,400
Michal_LFC
Author by

Michal_LFC

Updated on July 09, 2022

Comments

  • Michal_LFC
    Michal_LFC almost 2 years

    I'm trying to bind list to gridview. Situation is like this: I take data from .txt file, later I put it inside first list List<Mycolumns>. I have data in list (with 3 separated columns) that I created. I am taking data from one of the columns called System_Description. Now I would like to show this data in gridview, but only thing that I get is length of each row. How should I fix it? Here is my code.

    private void button7_Click(object sender, EventArgs e)
        {
            List<MyColumns> list = new List<MyColumns>();
    
            OpenFileDialog openFile1 = new OpenFileDialog();
            openFile1.Multiselect = true;
    
            if (openFile1.ShowDialog() != DialogResult.Cancel)
            {
                foreach (string filename in openFile1.FileNames)
                {
                    using (StreamReader sr = new StreamReader(filename))
                    {
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            string[] _columns = line.Split(",".ToCharArray());
                            MyColumns mc = new MyColumns();
                            mc.Time = _columns[0];
                            mc.System_Description = _columns[1];
                            mc.User_Description = _columns[2];
                            list.Add(mc);
                        }
                    }
                }
                DataTable ListAsDataTable = BuildDataTable<MyColumns>(list);
                DataView ListAsDataView = ListAsDataTable.DefaultView;
                this.dataGridView1.DataSource = view = ListAsDataView;
                this.dataGridView1.AllowUserToAddRows = false;
                dataGridView1.ClearSelection();
            }
    
            List<string> description = list.Select(x => x.System_Description).ToList<string>();
            this.dataGridView2.DataSource = description;
    
        }
    class MyColumns
    {
        public string Time { get; set; }
        public string System_Description { get; set; }
        public string User_Description { get; set; }
    }
    

    EDIT:

    I've read that DataBind() works for Web form, my app is desktop app. What should I do now?