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......
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| 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 |
| |||
| 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 |
| |||
| 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 |
| |||
| 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);
}
}
}
__________________ Sathish Kumar.R ![]() Knowledge is meant to SHARE |
| |||
| 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);
__________________ Sathish Kumar.R ![]() Knowledge is meant to SHARE |
| |||
| 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);
}
}
__________________ Sathish Kumar.R ![]() Knowledge is meant to SHARE |
| |||
| 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 |
| |||
| 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);
} |
| |||
| 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);
} |
| |||
| 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 |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Paging in Grid | ||||