Friday 1 November 2013

DataGridView , show custiom column and row headers , win forms .net

Recently one of my friend requested to show how to use custom header for columns for DataGridVew in WinForms , I worked on that and not only customize column headers but also row headers. Let's start this , first step is we required a model to show data into grid ( what are the fields in our collection or in database).
Our model :


    class CustomModel
    {
        public string Title {  get;set; }
        public string Detail  { get;set;  }
    }

These are two fields we want to show in gridview.

Now second step is to create a collection to bind to our gridview, and here is the all remaning code ,put it into your Form1_Load method like this :

   private void Form1_Load(object sender, EventArgs e)
        {
            List<CustomModel> dataList=new List<CustomModel>();

            dataList.Add(new CustomModel(){Title = "title1", Detail = "detail1"});
            dataList.Add(new CustomModel(){Title = "title2", Detail = "detail2"});

            dataGridView1.Columns.Clear();
            DataGridViewTextBoxColumn title = new DataGridViewTextBoxColumn();
            title.DataPropertyName = "Title";
            title.HeaderText = "Title";      
            dataGridView1.Columns.Add(title);

            DataGridViewTextBoxColumn description = new DataGridViewTextBoxColumn();
            description.DataPropertyName = "Detail";
            description.HeaderText = "Detail";  
            dataGridView1.Columns.Add(description);
         
            dataGridView1.DataSource = dataList;

            /* Create the row headers */
            int rowNumber = 1;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                row.HeaderCell.Value = "R" + rowNumber;
                rowNumber++;
            }

            // set rows headers width according to its text
            dataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            dataGridView1.Show();
        }





And that's simply it , enjoy :)

No comments:

Post a Comment