Click here to Skip to main content
12,698,012 members (24,748 online)
Click here to Skip to main content
Add your own
alternative version


23 bookmarked

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


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) <BR>  {<BR>   try<BR>   {<BR>    base.Paint(g,Bounds,Source,RowNum,BackBrush,ForeBrush,AlignToRight);<BR>    object o = GetColumnValueAtRow(Source, RowNum);<BR>    string textval ;<BR>    if(o==null || o==DBNull.Value)<BR>     textval = this.NullText;<BR>    else<BR>     textval = o.ToString();<BR>    if (textval == "Y")<BR>     System.Windows.Forms.ControlPaint.DrawRadioButton(g,Bounds.X,Bounds.Y,20,16,System.Windows.Forms.ButtonState.Checked);<BR>    else<BR>     System.Windows.Forms.ControlPaint.DrawRadioButton(g,Bounds.X,Bounds.Y,20,16,System.Windows.Forms.ButtonState.Normal);<BR>   }
   catch(Exception ex)<BR>   {<BR>    //MessageBox.Show(ex.Message);<BR>   }<BR>  }

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)<BR>  {
   DataGrid.HitTestInfo hti = this.DataGridTableStyle.DataGrid.HitTest( e.X, e.Y );<BR>   if(hti.Column != this.ColumnNumber)<BR>    return;<BR>   if ( e.Button == MouseButtons.Left && <BR>    hti.Type == DataGrid.HitTestType.Cell ) <BR>   {
    Click( new RadioButtonColumnEventArgs( hti.Row, hti.Column));

   }<BR>  }

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()<BR>  {<BR>   DataSet DataSetMain = new DataSet();<BR>   DataSetMain = GetDataSet();<BR>   datasetCategories1.Merge(DataSetMain);<BR>   RadioButtonColumnStyle RadioColumnStyleObject = null;<BR>   FlatLabelColumnStyle FlatColumnStyleObject = null;<BR>   ButtonColumnStyle ButtonColumnStyleObject=null;
   try<BR>   {<BR>    DataGridTableStyle GridTableStyle = new DataGridTableStyle();    <BR>    GridTableStyle.MappingName="Table";<BR>    GridTableStyle.BackColor = Color.FromArgb(220,229,234);<BR>    GridTableStyle.HeaderForeColor = Color.Navy;<BR>    GridTableStyle.AllowSorting=false;<BR>    GridTableStyle.HeaderFont = new Font("Microsoft Sans Serif", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));<BR>    GridTableStyle.HeaderBackColor=Color.FromArgb(220, 229, 234);<BR>    GridTableStyle.HeaderForeColor=Color.Black;<BR>    GridTableStyle.GridLineStyle = DataGridLineStyle.None;<BR>    if(datasetCategories1.Tables.Count>0)
    {     <BR>     GridTableStyle.GridColumnStyles.Clear();<BR>     GridTableStyle.RowHeadersVisible=false;<BR>     for(int i=0;i <datasetCategories1.Tables["Table"].Columns.Count; ++i)<BR>     {<BR>      if(datasetCategories1.Tables["Table"].Columns[i].ColumnName=="DeleteButton")<BR>      {<BR>       Bitmap BitmapObjectDelete = new Bitmap(path + "<A href="file://Images//deleteIcon.GIF">file://Images//deleteIcon.GIF</A>");<BR>       Bitmap BitmapObjectPressed = new Bitmap(path + "<A href="file://Images//deleteIcon.GIF">file://Images//deleteIcon.GIF</A>");<BR>       ButtonColumnStyleObject = new ButtonColumnStyle(i,BitmapObjectDelete,BitmapObjectPressed);<BR>       ButtonColumnStyleObject.HeaderText =  "";<BR>       ButtonColumnStyleObject.MappingName =  "DeleteButton";<BR>       ButtonColumnStyleObject.CellButtonClicked -= new ButtonColumnEventHandler(ButtonColumnStyleObject_Click);<BR>       ButtonColumnStyleObject.CellButtonClicked += new ButtonColumnEventHandler(ButtonColumnStyleObject_Click);<BR>       dataGrid1.MouseDown += new MouseEventHandler(ButtonColumnStyleObject.HandleMouseDown);<BR>       dataGrid1.MouseUp += new MouseEventHandler(ButtonColumnStyleObject.HandleMouseUp);<BR>       dataGrid1.MouseMove += new MouseEventHandler(ButtonColumnStyleObject.HandleMouseMove);<BR>       GridTableStyle.GridColumnStyles.Add(ButtonColumnStyleObject);<BR>      }
      else if(datasetCategories1.Tables["Table"].Columns[i].ColumnName=="RadioButton")<BR>      {<BR>       /*for Radio Button */<BR>       RadioColumnStyleObject = new RadioButtonColumnStyle();<BR>       RadioColumnStyleObject.HeaderText = "";<BR>       RadioColumnStyleObject.MappingName =  "RadioButton";<BR>       RadioColumnStyleObject.Alignment = HorizontalAlignment.Center;           <BR>       RadioColumnStyleObject.ReadOnly = false;<BR>       RadioColumnStyleObject.Width = 30;<BR>       RadioColumnStyleObject.ColumnNumber= 1 ;<BR>       RadioColumnStyleObject.Click += new RadioButtonColumnStyle.RadioButtonColumnClickHandler(RadioColumnStyle_Click);<BR>       GridTableStyle.GridColumnStyles.Add(RadioColumnStyleObject); <BR>      }<BR>      else<BR>      {         <BR>      <BR>       if(datasetCategories1.Tables["Table"].Columns[i].ColumnName=="CategoryName" || datasetCategories1.Tables["Table"].Columns[i].ColumnName=="Description" )<BR>       {<BR>        FlatColumnStyleObject = new FlatLabelColumnStyle();<BR>        switch (datasetCategories1.Tables["Table"].Columns[i].ColumnName)<BR>        {  <BR>         case "CategoryName":<BR>          FlatColumnStyleObject.HeaderText ="CategoryName";<BR>          FlatColumnStyleObject.Width = 100;<BR>          break;<BR>         case "Description":<BR>          FlatColumnStyleObject.HeaderText ="Description";<BR>          FlatColumnStyleObject.Width = 220;<BR>          break;<BR>        }<BR>        FlatColumnStyleObject.MappingName = datasetCategories1.Tables["Table"].Columns[i].ColumnName;<BR>        FlatColumnStyleObject.linecolor=Color.Brown;<BR>        FlatColumnStyleObject.showline = true;<BR>        GridTableStyle.GridColumnStyles.Add(FlatColumnStyleObject);<BR>       }<BR>      }<BR>     }<BR>    }<BR>    dataViewCategories = datasetCategories1.Tables["Table"].DefaultView;<BR>    dataGrid1.DataSource= dataViewCategories;<BR>    dataGrid1.TableStyles.Clear();<BR>    GridTableStyle.PreferredRowHeight = 25;<BR>    dataGrid1.TableStyles.Add(GridTableStyle); <BR>   }
   catch(Exception ex)<BR>   {<BR>    MessageBox.Show(ex.ToString());<BR>   }


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)<BR>  {<BR>   dataViewCategories.AllowEdit = true;<BR>   try<BR>   {
    dataViewCategories.RowFilter = "RadioButton='Y'";<BR>    if(dataViewCategories.Count == 1)<BR>    {<BR>     this.BindingContext[dataViewCategories].Position = 0;<BR>     DataRowView drv1 = (DataRowView)this.BindingContext[dataViewCategories].Current;<BR>     drv1["RadioButton"] = "N";<BR>     this.BindingContext[dataViewCategories].EndCurrentEdit();<BR>    }<BR>    dataViewCategories.RowFilter = "";<BR>    this.BindingContext[dataViewCategories].Position = e.RowIndex;<BR>    DataRowView drv = (DataRowView)this.BindingContext[dataViewCategories].Current;<BR>    drv["RadioButton"] = "Y";<BR>    this.BindingContext[dataViewCategories].EndCurrentEdit();<BR>    CatName.Text = drv["CategoryName"].ToString();<BR>    Description.Text = drv["Description"].ToString();<BR>   }
   catch(Exception ex)<BR>   {<BR>    MessageBox.Show(ex.Message);<BR>   }<BR>  }

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.



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


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.

You may also be interested in...


Comments and Discussions

Generalon refresh radio button not checked Pin
cbmsuresh22-Oct-08 3:54
membercbmsuresh22-Oct-08 3:54 
QuestionDataGrid Pin
Member 47502139-Mar-08 13:53
memberMember 47502139-Mar-08 13:53 
GeneralClick event is being raised twice Pin
Mithun_Patel27-Nov-07 13:39
memberMithun_Patel27-Nov-07 13:39 
QuestionAdd Combo In DataGrid Pin
Member #394563821-Mar-07 5:29
memberMember #394563821-Mar-07 5:29 
Questionadd data Pin
Member #394563821-Mar-07 5:27
memberMember #394563821-Mar-07 5:27 
QuestionProlem In Running Program Pin
mshariq14-Mar-07 23:11
membermshariq14-Mar-07 23:11 
AnswerRe: Prolem In Running Program Pin
Preeteesh Kakkar14-Mar-07 23:53
memberPreeteesh Kakkar14-Mar-07 23:53 
GeneralRe: Prolem In Running Program Pin
mshariq15-Mar-07 0:29
membermshariq15-Mar-07 0:29 
GeneralAdding Image on RadioButtonList Pin
nclauder6-Mar-07 20:14
membernclauder6-Mar-07 20:14 
GeneralRe: Adding Image on RadioButtonList Pin
Preeteesh Kakkar6-Mar-07 20:54
memberPreeteesh Kakkar6-Mar-07 20:54 
GeneralRe: Adding Image on RadioButtonList Pin
nclauder8-Mar-07 22:26
membernclauder8-Mar-07 22:26 
QuestionThe question about "DatasetCategories.cs" Pin
Bob.Zhong9-Feb-07 23:17
memberBob.Zhong9-Feb-07 23:17 
AnswerRe: The question about "DatasetCategories.cs" Pin
Preeteesh Kakkar10-Feb-07 19:07
memberPreeteesh Kakkar10-Feb-07 19:07 
GeneralRe: The question about "DatasetCategories.cs" Pin
Bob.Zhong11-Feb-07 19:37
memberBob.Zhong11-Feb-07 19:37 
GeneralRe: The question about "DatasetCategories.cs" Pin
Preeteesh Kakkar6-Mar-07 21:06
memberPreeteesh Kakkar6-Mar-07 21:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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
Web01 | 2.8.170118.1 | Last Updated 27 Oct 2006
Article Copyright 2006 by Preeteesh Kakkar
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid