Click here to Skip to main content
Click here to Skip to main content

Customizing Columns in Datagrid – Adding Image and Radio Button to windows Datagrid

, 27 Oct 2006
Rate this:
Please Sign up or sign in to vote.
Adding Radio and Delete button in Windows form datagrid

Introduction

Customizing Columns in Datagrid – Adding Image and Radio Button to windows Datagrid

Many of us have always used datagrid in our web and windows applications. In web we can easily display checkbox, radio buttons, image button etc by using template columns. Adding radio button or image button in windows data grid is not that easy as it’s in web. We can’t directly drag and drop a radio button inside a windows datagrid; instead we require our custom radio button or better said a CustomDatagridColumn style for radio button. This is what I will try to show in this article. I will try to explain most part of code so as to make you understand how this stuff works. Also we will use typed dataset in this example.

I would recommend you to download zipped code file and have a short look at code.

 Lets 1st start looking at file RadioButtonColumnStyle.cs, here we have overridden two functions – Paint and SetDataGridInColumn

protected override void Paint(Graphics g,Rectangle Bounds,CurrencyManager Source,int RowNum, Brush BackBrush ,Brush ForeBrush ,bool AlignToRight) 
  {
   try
   {
    base.Paint(g,Bounds,Source,RowNum,BackBrush,ForeBrush,AlignToRight);
    object o = GetColumnValueAtRow(Source, RowNum);
    string textval ;
    if(o==null || o==DBNull.Value)
     textval = this.NullText;
    else
     textval = o.ToString();
    if (textval == "Y")
     System.Windows.Forms.ControlPaint.DrawRadioButton(g,Bounds.X,Bounds.Y,20,16,System.Windows.Forms.ButtonState.Checked);
    else
     System.Windows.Forms.ControlPaint.DrawRadioButton(g,Bounds.X,Bounds.Y,20,16,System.Windows.Forms.ButtonState.Normal);
   }

   catch(Exception ex)
   {
    //MessageBox.Show(ex.Message);
   }
  }

Here we see that we are calling a function called GetColumnValueAtRow. This function gets the value of the cell/column in particular row as specified. Now in our case if the value we got is “Y”, we draw a radiobutton using DrawRadioButton in checked state else we draw it in Normal state.

In other override function SetDataGridInColumn, We declare mouse event handler for those datagrids which uses radiobuttonColumnstyle.


private void DataGrid_MouseDown(object sender, MouseEventArgs e)
  {

   DataGrid.HitTestInfo hti = this.DataGridTableStyle.DataGrid.HitTest( e.X, e.Y );
   if(hti.Column != this.ColumnNumber)
    return;
   if ( e.Button == MouseButtons.Left &&
    hti.Type == DataGrid.HitTestType.Cell )
   {

    Click( new RadioButtonColumnEventArgs( hti.Row, hti.Column));

   }
  }

The Above code shows the event handler for MouseDown, in this we 1st gets the area hit by mouse using HitTest function. After that we call click function passing the required arguments. This event is implemented in form1.cs file.

Now let’s see FillDataGrid function in form1.cs file code.

private void FillDataGrid()
  {
   DataSet DataSetMain = new DataSet();
   DataSetMain = GetDataSet();
   datasetCategories1.Merge(DataSetMain);
   RadioButtonColumnStyle RadioColumnStyleObject = null;
   FlatLabelColumnStyle FlatColumnStyleObject = null;
   ButtonColumnStyle ButtonColumnStyleObject=null;

   try
   {
    DataGridTableStyle GridTableStyle = new DataGridTableStyle();    
    GridTableStyle.MappingName="Table";
    GridTableStyle.BackColor = Color.FromArgb(220,229,234);
    GridTableStyle.HeaderForeColor = Color.Navy;
    GridTableStyle.AllowSorting=false;
    GridTableStyle.HeaderFont = new Font("Microsoft Sans Serif", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
    GridTableStyle.HeaderBackColor=Color.FromArgb(220, 229, 234);
    GridTableStyle.HeaderForeColor=Color.Black;
    GridTableStyle.GridLineStyle = DataGridLineStyle.None;
    if(datasetCategories1.Tables.Count>0)

    {     
     GridTableStyle.GridColumnStyles.Clear();
     GridTableStyle.RowHeadersVisible=false;
     for(int i=0;i <datasetCategories1.Tables["Table"].Columns.Count; ++i)
     {
      if(datasetCategories1.Tables["Table"].Columns[i].ColumnName=="DeleteButton")
      {
       Bitmap BitmapObjectDelete = new Bitmap(path + "file://Images//deleteIcon.GIF");
       Bitmap BitmapObjectPressed = new Bitmap(path + "file://Images//deleteIcon.GIF");
       ButtonColumnStyleObject = new ButtonColumnStyle(i,BitmapObjectDelete,BitmapObjectPressed);
       ButtonColumnStyleObject.HeaderText =  "";
       ButtonColumnStyleObject.MappingName =  "DeleteButton";
       ButtonColumnStyleObject.CellButtonClicked -= new ButtonColumnEventHandler(ButtonColumnStyleObject_Click);
       ButtonColumnStyleObject.CellButtonClicked += new ButtonColumnEventHandler(ButtonColumnStyleObject_Click);
       dataGrid1.MouseDown += new MouseEventHandler(ButtonColumnStyleObject.HandleMouseDown);
       dataGrid1.MouseUp += new MouseEventHandler(ButtonColumnStyleObject.HandleMouseUp);
       dataGrid1.MouseMove += new MouseEventHandler(ButtonColumnStyleObject.HandleMouseMove);
       GridTableStyle.GridColumnStyles.Add(ButtonColumnStyleObject);
      }

      else if(datasetCategories1.Tables["Table"].Columns[i].ColumnName=="RadioButton")
      {
       /*for Radio Button */
       RadioColumnStyleObject = new RadioButtonColumnStyle();
       RadioColumnStyleObject.HeaderText = "";
       RadioColumnStyleObject.MappingName =  "RadioButton";
       RadioColumnStyleObject.Alignment = HorizontalAlignment.Center;           
       RadioColumnStyleObject.ReadOnly = false;
       RadioColumnStyleObject.Width = 30;
       RadioColumnStyleObject.ColumnNumber= 1 ;
       RadioColumnStyleObject.Click += new RadioButtonColumnStyle.RadioButtonColumnClickHandler(RadioColumnStyle_Click);
       GridTableStyle.GridColumnStyles.Add(RadioColumnStyleObject); 
      }
      else
      {         
      
       if(datasetCategories1.Tables["Table"].Columns[i].ColumnName=="CategoryName" || datasetCategories1.Tables["Table"].Columns[i].ColumnName=="Description" )
       {
        FlatColumnStyleObject = new FlatLabelColumnStyle();
        switch (datasetCategories1.Tables["Table"].Columns[i].ColumnName)
        {  
      
   case "CategoryName":
          FlatColumnStyleObject.HeaderText ="CategoryName";
          FlatColumnStyleObject.Width = 100;
          break;
         case "Description":
          FlatColumnStyleObject.HeaderText ="Description";
          FlatColumnStyleObject.Width = 220;
          break;
        }
        FlatColumnStyleObject.MappingName = datasetCategories1.Tables["Table"].Columns[i].ColumnName;
        FlatColumnStyleObject.linecolor=Color.Brown;
        FlatColumnStyleObject.showline = true;
        GridTableStyle.GridColumnStyles.Add(FlatColumnStyleObject);
       }
      }
     }
    }
    dataViewCategories = datasetCategories1.Tables["Table"].DefaultView;
    dataGrid1.DataSource= dataViewCategories;
    dataGrid1.TableStyles.Clear();
    GridTableStyle.PreferredRowHeight = 25;
    dataGrid1.TableStyles.Add(GridTableStyle); 
   }

   catch(Exception ex)
   {
    MessageBox.Show(ex.ToString());
   }

  }

In this function we create our custom GridTableStyle and add it to our datagrid. Also we have binding of datagrid1 to dataviewCategories which has binding to datasetCategories. We created an event handler for Click event of RadioButtonColumnClickHandler delegate. Below is the code for it.

private void RadioColumnStyle_Click(RadioButtonColumnEventArgs e)
  {
   dataViewCategories.AllowEdit = true;
   try
   {

    dataViewCategories.RowFilter = "RadioButton='Y'";
    if(dataViewCategories.Count == 1)
    {
     this.BindingContext[dataViewCategories].Position = 0;
     DataRowView drv1 = (DataRowView)this.BindingContext[dataViewCategories].Current;
     drv1["RadioButton"] = "N";
     this.BindingContext[dataViewCategories].EndCurrentEdit();
    }
    dataViewCategories.RowFilter = "";
    this.BindingContext[dataViewCategories].Position = e.RowIndex;
    DataRowView drv = (DataRowView)this.BindingContext[dataViewCategories].Current;
    drv["RadioButton"] = "Y";
    this.BindingContext[dataViewCategories].EndCurrentEdit();
    CatName.Text = drv["CategoryName"].ToString();
    Description.Text = drv["Description"].ToString();
   }

   catch(Exception ex)
   {
    MessageBox.Show(ex.Message);
   }
  }

In this we first check if there is any radio button already selected, if so we deselect it by editing that row and then we get the clicked row index by using e.RowIndex and assign it to the dataViewCategories current position. Then we select that row by editing it and also assign the corresponding textboxes with required values.

Similarly we have implemented FlatLabelColumnStyle and ButtonColumnStyle. Both are quite simple to understand and have been properly implemented in code. If any one of you have queries on any part of it please let me know.

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Preeteesh Kakkar
Web Developer
India India
I started playing with computers around 5 years back when i got my PC, since then i have been love with Software programming, Security. I have done programming in C, C++, C#, Core Java , Applets and etc. My interest includes security, vulnerability assesment, learning to write exploits and writing some good articles.

Comments and Discussions

 
Generalon refresh radio button not checked Pinmembercbmsuresh22-Oct-08 3:54 
QuestionDataGrid PinmemberMember 47502139-Mar-08 13:53 
GeneralClick event is being raised twice PinmemberMithun_Patel27-Nov-07 13:39 
QuestionAdd Combo In DataGrid PinmemberMember #394563821-Mar-07 5:29 
Questionadd data PinmemberMember #394563821-Mar-07 5:27 
QuestionProlem In Running Program Pinmembermshariq14-Mar-07 23:11 
AnswerRe: Prolem In Running Program PinmemberPreeteesh Kakkar14-Mar-07 23:53 
GeneralRe: Prolem In Running Program Pinmembermshariq15-Mar-07 0:29 
GeneralAdding Image on RadioButtonList Pinmembernclauder6-Mar-07 20:14 
GeneralRe: Adding Image on RadioButtonList PinmemberPreeteesh Kakkar6-Mar-07 20:54 
GeneralRe: Adding Image on RadioButtonList Pinmembernclauder8-Mar-07 22:26 
QuestionThe question about "DatasetCategories.cs" PinmemberBob.Zhong9-Feb-07 23:17 
AnswerRe: The question about "DatasetCategories.cs" PinmemberPreeteesh Kakkar10-Feb-07 19:07 
GeneralRe: The question about "DatasetCategories.cs" PinmemberBob.Zhong11-Feb-07 19:37 
GeneralRe: The question about "DatasetCategories.cs" PinmemberPreeteesh Kakkar6-Mar-07 21:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 27 Oct 2006
Article Copyright 2006 by Preeteesh Kakkar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid