locked
how to bind List to DataGridView? RRS feed

  • Question

  • I want to bind a list to datagridview, but the column.count is always 0; The following is the code snippet.

            struct AccRec
            {
                public int PatientId;
                public string PatName;
                public int AccountId;
            }

           public void ShowGrid(object sender, EventArgs e)

           {
                    AccRec accRec = new AccRec();
                    List<AccRec> accList = new List<AccRec>();
                    int i = 0;
                    while (i < 3)
                    {
                        accRec.PatientId = 1;
                        accRec.PatName = "Surname,FirstName";
                        accRec.AccountId = 1;
                        accList.Add(accRec);
                        i++;
                    }

                        dataGridView2.DataSource = accList; //not working

                        //dataGridView2.DataSource = accList.ToList();  //not working

                        //dataGridView2.DataSource = accList.AsEnumerable();  //not working

                        dataGridView2.Columns["PatientId"].DisplayIndex = 0;  //throw an error "Object reference not set to an instance of an object."
                        dataGridView2.Columns["AccountId"].DisplayIndex = 1;
                        dataGridView2.Columns["PatName"].DisplayIndex = 2;

             }

     

    Friday, January 28, 2011 5:22 AM

Answers

  • YOu are missing get,set accessors in the struct - so the data source can get the data from some where. I have rearaged the code a bit, so it looks more "readable", and it works:

    namespace Jan28DGV_BindList
    {
      public partial class Form1 : Form
      {
        private List<AccRec> accList;
        public Form1()
        {
          InitializeComponent();
          InitializingBS();
          CreatingGrid();
        }
    
        public void CreatingGrid()
        {
          dataGridView1.AutoGenerateColumns = false;
          dataGridView1.AllowUserToAddRows = false;
          dataGridView1.DataSource = accList;
    
          DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
          column1.Name = "PatientId";
          column1.HeaderText = "Patient id";
          column1.DataPropertyName = "PatientId";
          dataGridView1.Columns.Add(column1);
    
          DataGridViewTextBoxolumn column2 = new DataGridViewTextBoxColumn();
          column2.Name = "AccountId";
          column2.HeaderText = "Account id";
          column2.DataPropertyName = "AccountId";
          dataGridView1.Columns.Add(column2);
    
          DataGridViewTextBoxColumn column3 = new DataGridViewTextBoxColumn();
          column3.Name = "PatName";
          column3.HeaderText = "Pat name";
          column3.DataPropertyName = "PatName";
          dataGridView1.Columns.Add(column3);
        }
    
        public void InitializingBS()
        {
          accList = new List<AccRec>();
          for (int i = 0; i < 3; i++)
          {
            AccRec accRec = new AccRec();
            accRec.PatientId = i + 1;
            accRec.PatName = "Surname,FirstName";
            accRec.AccountId = i + 2;
            accList.Add(accRec);
          }
        }
      }
    
      struct AccRec
      {
        public int PatientId { get; set; }
        public int AccountId { get; set; }
        public string PatName { get; set; }
      }
    }
    

     

    Hope it helps,

    Mitja

     

    • Marked as answer by peter 9 Monday, January 31, 2011 12:40 AM
    Friday, January 28, 2011 10:16 AM

All replies

  • hi,

    if u dont have any issue with datatable then u can try this way.....

    DataTable dt = null;
    
    void FillDt()
    {
     if (dt == null)
     {
      dt = new System.Data.DataTable();
      dt.Columns.Add("PatientID");
      dt.Columns.Add("PatientName");
     }
    
     for(int i = 1; i < 30; i++)
     { 
      dt.Rows.Add( i ,"Name -" + i);
     } 
      
     dataGridView1.DataSource = dt.DefaultView;
    }
    
    


    Nagarjuna Dilip
    Friday, January 28, 2011 5:50 AM
  • Or add the columns @ design time r runtime and then bind the collection object.

    struct AccRec
      {
       public int PatientId;
       public string PatName;
       public int AccountId;
      }
    
      public void ShowGrid(object sender, EventArgs e)
    
      {
        AccRec accRec = new AccRec();
        List<AccRec> accList = new List<AccRec>();
        int i = 0;
        while (i < 3)
        {
         accRec.PatientId = 1;
         accRec.PatName = "Surname,FirstName";
         accRec.AccountId = 1;
         accList.Add(accRec);
         i++;
        }
        dataGridView2.Columns.Add("PatientId");
        dataGridView2.Columns.Add("AccountId");
        dataGridView2.Columns.Add("PatName");
    
        dataGridView2.DataSource = accList; 
        dataGridView2.Columns["PatientId"].DisplayIndex = 0; 
        dataGridView2.Columns["AccountId"].DisplayIndex = 1;
        dataGridView2.Columns["PatName"].DisplayIndex = 2;
    
       }


    Nagarjuna Dilip
    Friday, January 28, 2011 5:53 AM
  • YOu are missing get,set accessors in the struct - so the data source can get the data from some where. I have rearaged the code a bit, so it looks more "readable", and it works:

    namespace Jan28DGV_BindList
    {
      public partial class Form1 : Form
      {
        private List<AccRec> accList;
        public Form1()
        {
          InitializeComponent();
          InitializingBS();
          CreatingGrid();
        }
    
        public void CreatingGrid()
        {
          dataGridView1.AutoGenerateColumns = false;
          dataGridView1.AllowUserToAddRows = false;
          dataGridView1.DataSource = accList;
    
          DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
          column1.Name = "PatientId";
          column1.HeaderText = "Patient id";
          column1.DataPropertyName = "PatientId";
          dataGridView1.Columns.Add(column1);
    
          DataGridViewTextBoxolumn column2 = new DataGridViewTextBoxColumn();
          column2.Name = "AccountId";
          column2.HeaderText = "Account id";
          column2.DataPropertyName = "AccountId";
          dataGridView1.Columns.Add(column2);
    
          DataGridViewTextBoxColumn column3 = new DataGridViewTextBoxColumn();
          column3.Name = "PatName";
          column3.HeaderText = "Pat name";
          column3.DataPropertyName = "PatName";
          dataGridView1.Columns.Add(column3);
        }
    
        public void InitializingBS()
        {
          accList = new List<AccRec>();
          for (int i = 0; i < 3; i++)
          {
            AccRec accRec = new AccRec();
            accRec.PatientId = i + 1;
            accRec.PatName = "Surname,FirstName";
            accRec.AccountId = i + 2;
            accList.Add(accRec);
          }
        }
      }
    
      struct AccRec
      {
        public int PatientId { get; set; }
        public int AccountId { get; set; }
        public string PatName { get; set; }
      }
    }
    

     

    Hope it helps,

    Mitja

     

    • Marked as answer by peter 9 Monday, January 31, 2011 12:40 AM
    Friday, January 28, 2011 10:16 AM
  • This is the "shorter version of the CreatingGrid() method, so you dont need to create all the columns individually - even if it doesn`t hurt (I always create column in a long way, and set all the necessary). Anyway, here its the code:

        public void CreatingGrid()
        {
          dataGridView1.AutoGenerateColumns = false;
          dataGridView1.AllowUserToAddRows = false;
          dataGridView1.DataSource = accList;
    
          dataGridView1.Columns.Add("PatientId", "Patient id");
          dataGridView1.Columns.Add("AccountId", "Account id");
          dataGridView1.Columns.Add("PatName", "Pat name");
    
          dataGridView1.Columns[0].DataPropertyName = "PatientId";
          dataGridView1.Columns[1].DataPropertyName = "AccountId";
          dataGridView1.Columns[2].DataPropertyName = "PatName";
        }
    

    Friday, January 28, 2011 10:24 AM
  • I would do it in the code behind

    Page's html

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server">
            </asp:GridView>
        
        </div>
        </form>
    </body>
    </html>

    Code behind file 

    using System;

    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Collections.Generic;

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<Client> lst = new List<Client>();
            lst.Add(new Client("Ken", 39));
            lst.Add(new Client("Cor", 48));

            GridView1.DataSource = lst;
            GridView1.DataBind();
        }
    }
    public class Client
    {

        public Client(string Name, int Age)
        {
            _Name = Name;
            _Age = Age;
        }

        private int _Age;

        public int Age
        {
            get { return _Age; }
            set { _Age = value; }
        }

        private string _Name;

        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
        
    }
    Sankarshan Parida
    Saturday, January 29, 2011 9:48 AM
  • thank u very much. It works.
    Monday, January 31, 2011 12:40 AM