Click here to Skip to main content
15,885,948 members
Articles / Programming Languages / C#
Article

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

Rate me:
Please Sign up or sign in to vote.
3.75/5 (8 votes)
27 Oct 20064 min read 81.1K   1.5K   23   15
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) <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.

 

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


Written By
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 Pin
cbmsuresh22-Oct-08 2:54
cbmsuresh22-Oct-08 2:54 
QuestionDataGrid Pin
Member 47502139-Mar-08 12:53
Member 47502139-Mar-08 12:53 
GeneralClick event is being raised twice Pin
Mithun_Patel27-Nov-07 12:39
Mithun_Patel27-Nov-07 12:39 
QuestionAdd Combo In DataGrid Pin
nileshr200121-Mar-07 4:29
nileshr200121-Mar-07 4:29 
Questionadd data Pin
nileshr200121-Mar-07 4:27
nileshr200121-Mar-07 4:27 
QuestionProlem In Running Program Pin
mshariq14-Mar-07 22:11
mshariq14-Mar-07 22:11 
AnswerRe: Prolem In Running Program Pin
Preeteesh Kakkar14-Mar-07 22:53
Preeteesh Kakkar14-Mar-07 22:53 
GeneralRe: Prolem In Running Program Pin
mshariq14-Mar-07 23:29
mshariq14-Mar-07 23:29 
GeneralAdding Image on RadioButtonList Pin
nclauder6-Mar-07 19:14
nclauder6-Mar-07 19:14 
GeneralRe: Adding Image on RadioButtonList Pin
Preeteesh Kakkar6-Mar-07 19:54
Preeteesh Kakkar6-Mar-07 19:54 
GeneralRe: Adding Image on RadioButtonList Pin
nclauder8-Mar-07 21:26
nclauder8-Mar-07 21:26 
QuestionThe question about "DatasetCategories.cs" Pin
Bob.Zhong9-Feb-07 22:17
Bob.Zhong9-Feb-07 22:17 
AnswerRe: The question about "DatasetCategories.cs" Pin
Preeteesh Kakkar10-Feb-07 18:07
Preeteesh Kakkar10-Feb-07 18:07 
GeneralRe: The question about "DatasetCategories.cs" Pin
Bob.Zhong11-Feb-07 18:37
Bob.Zhong11-Feb-07 18:37 
GeneralRe: The question about "DatasetCategories.cs" Pin
Preeteesh Kakkar6-Mar-07 20:06
Preeteesh Kakkar6-Mar-07 20: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.