IT Community - Software Programming, Web Development and Technical Support

C#.Net, ASP.Net Data Grid Frequently Asked Questions

This is a discussion on C#.Net, ASP.Net Data Grid Frequently Asked Questions within the C# Programming forums, part of the Software Development category; Hi Sathish.. How can I put a combobox in a column of a datagrid? thnkx......


Go Back   IT Community - Software Programming, Web Development and Technical Support > Software Development > C# Programming

Register FAQ Members List Calendar Mark Forums Read

Reply
 
LinkBack Thread Tools Display Modes
  #21 (permalink)  
Old 01-17-2008, 05:28 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How can I put a combobox in a column of a datagrid?

Hi Sathish..

How can I put a combobox in a column of a datagrid?


thnkx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #22 (permalink)  
Old 01-17-2008, 05:32 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Thumbs up Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi Deeban,
There are several ways to go about this task. The simplest way involves adding a single combobox to the DataGrid.Controls, and then selectively displaying it as needed when a combobox cell becomes the currentcell. All the work is done in a few event handlers and no overrides or derived classes are necessary.

The other techniques require you to derive a columnstyle. This implementation differs from other available columnstyle samples in that it derives from DataGridTextBoxColumn.

This derived DataGridTextBoxColumn does not implement a databound combobox where you can set its DataSource, DisplayMember, and ValueMember to bind the combobox to a foreign table.
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #23 (permalink)  
Old 01-17-2008, 05:32 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi Sathish...

Thanks for your reply... it would be great if you send me the sample code...


thanks again...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #24 (permalink)  
Old 01-17-2008, 05:34 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Thumbs up Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi,
This sample just attempts to replace the TextBox member of DataGridTextBoxColumn with a standard ComboBox member. Only two overrides need to be handled along with 2 events to get a functional implementation.

Here are the notes from the code that list the 3 steps to add a combobox to your datagrid.

Code:
 // Step 1. Derive a custom column style from DataGridTextBoxColumn 
 
     //     a) add a ComboBox member 
 
     // b) track when the combobox has focus in Enter and Leave events 
 
     // c) override Edit to allow the ComboBox to replace the TextBox 
 
     // d) override Commit to save the changed data 
 

 

 
     // Step 2 - Use the combo column style 
 
     // Add 1 col with combo style 
 
     DataGridComboBoxColumn ComboTextCol = new DataGridComboBoxColumn(); 
 
     ComboTextCol.MappingName = "custCity"; 
 
     ComboTextCol.HeaderText = "Customer Address"; 
 
     ComboTextCol.Width = 100; 
 
     ts1.GridColumnStyles.Add(ComboTextCol); 
 

 
     // Step 3 - Additional setup for Combo style 
 
     // a) make the row height a little larger to handle minimum combo height 
 
     ts1.PreferredRowHeight = ComboTextCol.ColumnComboBox.Height + 3; 
 
     // b) Populate the combobox somehow. It is a normal combobox, so whatever... 
 
     ComboTextCol.ColumnComboBox.Items.Clear(); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Chicago"); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Corvallis"); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Denver"); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Great Falls"); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Kansas City"); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Los Angeles"); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Raleigh"); 
 
     ComboTextCol.ColumnComboBox.Items.Add("Washington"); 
 

 
     // c) set the dropdown style of the combo... 
 
     ComboTextCol.ColumnComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #25 (permalink)  
Old 01-22-2008, 12:01 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How do I color a individual cell depending upon its value or some external method?

Hi All...

How do I color a individual cell depending upon its value or some external method?

In Datagrid..

thnx..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #26 (permalink)  
Old 01-22-2008, 12:02 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

I give three different methods for doing this.

# The first one overrides Paint in a derived columnstyle and sets the backcolor there.
# The second uses a delegate to set the color in the Paint override.
# The third method adds an event to the derived column style to allow you to set the color in an event handler.

I hope this will help you...
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #27 (permalink)  
Old 01-22-2008, 12:03 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How to : overrides Paint in a derived columnstyle and sets the backcolor?

Hi...

How to : overrides Paint in a derived columnstyle and sets the backcolor?

thnx..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #28 (permalink)  
Old 01-22-2008, 12:05 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

You can do this by deriving from DataGridTextBoxColumn and overriding the Paint method to conditionally set the backColor and foreColor. The sample code below colors any cell that starts with a letter higher than 'F'.


Code:
public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
     {
          protected override void Paint(System.Drawing.Graphics g,
               System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager
               source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush
               foreBrush, bool alignToRight)
          {
          // the idea is to conditionally set the foreBrush and/or backbrush
          // depending upon some criteria on the cell value
          // Here, we color anything that begins with a letter higher than 'F'
               try{
                    object o = this.GetColumnValueAtRow(source, rowNum);
                    if( o!= null)
                    {
                         char c = ((string)o)[0];
                         if( c > 'F')
                         {
                         // could be as simple as
                         // backBrush = new SolidBrush(Color.Pink);
                         // or something fancier...
                              backBrush = new LinearGradientBrush(bounds,
                                   Color.FromArgb(255, 200, 200),
                                   Color.FromArgb(128, 20, 20),
                                   LinearGradientMode.BackwardDiagonal);
                              foreBrush = new SolidBrush(Color.White);
                         }
                    }
               }
                catch(Exception ex){ /* empty catch */ }
               finally{
                    // make sure the base class gets called to do the drawing with
                    // the possibly changed brushes
                    base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
               }
          }
     }
I hope this will help you..
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #29 (permalink)  
Old 01-28-2008, 02:41 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How can I put a checkbox in a column of my DataGrid?

Hi all..

How can I put a checkbox in a column of my DataGrid?

thanks...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #30 (permalink)  
Old 01-28-2008, 02:44 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi...

You have to create a custom DataTableStyle that contains column styles for each column you want to display.Then You should add the column styles in the order you want them to appear. Here are the steps to add an string column, an int column and a bool check column to a DataGrid.


Code:
// code assumes you have a DataSet named myDataSet, a table named "EastCoastSales" and a DataGrid myDataGrid
//STEP 1: Create a DataTable style object and set properties if required.
     DataGridTableStyle ts1 = new DataGridTableStyle();

     //specify the table from dataset (required step)
     ts1.MappingName = "EastCoastSales";
     
     // Set other properties (optional step)
     ts1.AlternatingBackColor = Color.LightBlue;

//STEP 2: Create a string column and add it to the tablestyle
     DataGridColumnStyle TextCol = new DataGridTextBoxColumn();
     TextCol.MappingName = "custName"; //from dataset table
     TextCol.HeaderText = "Customer Name";
     TextCol.Width = 250;
     ts1.GridColumnStyles.Add(TextCol);

//STEP 3: Create an int column style and add it to the tablestyle
     //this requires setting the format for the column through its property descriptor
     PropertyDescriptorCollection pdc = this.BindingContext
           [myDataSet, "EastCoastSales"].GetItemProperties();

     //now created a formated column using the pdc
     DataGridDigitsTextBoxColumn csIDInt =
           new DataGridDigitsTextBoxColumn(pdc["CustID"], "i", true);
     csIDInt.MappingName = "CustID";
     csIDInt.HeaderText = "CustID";
     csIDInt.Width = 100;
     ts1.GridColumnStyles.Add(csIDInt);

//STEP 4: Add the checkbox
     DataGridColumnStyle boolCol = new DataGridBoolColumn();
     boolCol.MappingName = "Current";
     boolCol.HeaderText = "Info Current";

//uncomment this line to get a two-state checkbox
     //((DataGridBoolColumn)boolCol).AllowNull = false;

     boolCol.Width = 150;
     ts1.GridColumnStyles.Add(boolCol);

//STEP 5: Add the tablestyle to your datagrid's tablestlye collection
     myDataGrid.TableStyles.Add(ts1);
I hope this will help you..
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #31 (permalink)  
Old 01-28-2008, 02:45 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How can I restrict the keystrokes that will be accepted in a column of my datagrid?

Hi..

How can I restrict the keystrokes that will be accepted in a column of my datagrid?


thnx..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #32 (permalink)  
Old 01-28-2008, 02:46 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

You can create a custom column style and handle the KeyPress event of its TextBox member. Below is the code showing how this might be done.

Code:
public class DataGridDigitsTextBoxColumn : DataGridTextBoxColumn
{
     public DataGridDigitsTextBoxColumn(System.ComponentModel.PropertyDescriptor pd, string format, bool b)
               : base(pd, format, b)
     {
          this.TextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(HandleKeyPress);
     }

     private void HandleKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
     {
          //ignore if not digit or control key
          if(!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
               e.Handled = true;

          //ignore if more than 3 digits
          if(this.TextBox.Text.Length >= 3 && !char.IsControl(e.KeyChar))
               e.Handled = true;
     }

     protected override void Dispose(bool disposing)
     {
          if(disposing)
               this.TextBox.KeyPress -= new System.Windows.Forms.KeyPressEventHandler(HandleKeyPress);

          base.Dispose(disposing);
     }
}
Cheers..
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #33 (permalink)  
Old 01-28-2008, 02:47 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How do I make a field auto increment as new rows are added to my datagrid?

Hi..

How do I make a field auto increment as new rows are added to my datagrid?


thnx..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #34 (permalink)  
Old 01-28-2008, 02:48 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

HI..

You can do the page index option in datatable.. easily. here is the code implementation.

DataTable myTable = new DataTable("Customers");
...
DataColumn cCustID = new DataColumn("CustID", typeof(int));
cCustID.AutoIncrement = true;
cCustID.AutoIncrementSeed = 1;
cCustID.AutoIncrementStep = 1;
myTable.Columns.Add(cCustID);
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #35 (permalink)  
Old 01-29-2008, 03:08 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default How can I prevent a particular cell from being editable?

Hi..

How can I prevent a particular cell from being editable in a Datagrid?

thnx..
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #36 (permalink)  
Old 01-29-2008, 03:11 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

You can do this by deriving a custom column style and overriding its virtual Edit member. Below is an override that will prevent the cell in row 1 of the column from getting the edit focus.

If you want a more flexible solution, you could expose an event as part of your derived columnstyle that fires right before the call to the baseclass in the Edit override. This would allow the handler of the event to set the enable value depending upon the row and column parameters that are passed as part of the event args.

You could modify the eventargs to include a backcolor, and use this event to color cells based on row and column values.

Code:
//this override will prevent the cell in row 1 from getting the edit focus
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
     if(rowNum == 1)
          return;
     base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}
I hope this will help you...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #37 (permalink)  
Old 01-29-2008, 03:12 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default How do I move columns in a datagrid Using C#.Net?

Hi...

How do I move columns in a datagrid Using C#.Net?
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #38 (permalink)  
Old 01-29-2008, 03:13 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

The columns appear in the order that their column styles were added to the tablestyle being used by the grid. If you want to change this order, you would need to create a new table style, and add the columnstyles in the order you want things to appear. Here is some code snippets that suggest how to do this.

Code:
public void MoveColumn(DataGrid _dataGrid, string _mappingName, int fromCol, int toCol)
{
     if(fromCol == toCol) return;

     DataGridTableStyle oldTS = _dataGrid.TableStyles[_mappingName];
     DataGridTableStyle newTS = new DataGridTableStyle();
     newTS.MappingName = _mappingName;

     for(int i = 0; i < oldTS.GridColumnStyles.Count; ++i)
     {
          if(i != fromCol && fromCol < toCol)
               newTS.GridColumnStyles.Add(oldTS.GridColumnStyles[i]);
          if(i == toCol)
               newTS.GridColumnStyles.Add(oldTS.GridColumnStyles[fromCol]);
          if(i != fromCol && fromCol > toCol)
               newTS.GridColumnStyles.Add(oldTS.GridColumnStyles[i]);     
     }

     _dataGrid.TableStyles.Remove(oldTS);
     _dataGrid.TableStyles.Add(newTS);
}

//sample usage
private void button1_Click(object sender, System.EventArgs e)
{
     MoveColumn(myDataGrid, "Customers", 3, 1);
}
I hope this will help you..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #39 (permalink)  
Old 01-29-2008, 03:15 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

I would be greate if you provide me VB.Net Code.
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #40 (permalink)  
Old 01-29-2008, 03:15 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

Here is the VB.net Code.

Code:
[VB.NET]
Public Sub MoveColumn(_dataGrid As DataGrid, _mappingName As String, fromCol As Integer, toCol As Integer)
     If fromCol = toCol Then
          Return
     End If
     Dim oldTS As DataGridTableStyle = _dataGrid.TableStyles(_mappingName)
     Dim newTS As New DataGridTableStyle()
     newTS.MappingName = _mappingName

     Dim i As Integer
     i = 0
     While i < oldTS.GridColumnStyles.Count
          If i <> fromCol And fromCol < toCol Then
               newTS.GridColumnStyles.Add(oldTS.GridColumnStyles(i))
          End If
          If i = toCol Then
               newTS.GridColumnStyles.Add(oldTS.GridColumnStyles(fromCol))     
          End If
          If i <> fromCol And fromCol > toCol Then
               newTS.GridColumnStyles.Add(oldTS.GridColumnStyles(i))
          End If
          i = i + 1
     End While
     _dataGrid.TableStyles.Remove(oldTS)
     _dataGrid.TableStyles.Add(newTS)
End Sub 'MoveColumn

'sample usage
Private Sub button1_Click(sender As Object, e As System.EventArgs)
     MoveColumn(myDataGrid, "Customers", 3, 1)
End Sub 'button1_Click
Thnx..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Paging in Grid