Here are some frequently asked questions about Windows Forms and their answers.
Browse by Tags
All Tags » DataGrid (RSS)
-
|
To use custom ColumnStyles in the designer, you need to do three things. 1) Derive a CustomColumnStyle to implement the functionality you want. 2) Derive a DataGridTableStyle class and add a new GridColumnStyles property that uses this derived CollectionEditor...
|
-
|
This is possible if you assign a custom DataGridTableStyle to the DataGrid. The properties in the DataGridTableStyle will then replace certain properties in the DataGrid. Take a look at DataGrid class reference for a list of these properties. Contributed...
|
-
|
You can handle the DataGrid's DoubleClick event, and use the HitTest method to test if the double-click was on a column header. using System; using System.Drawing; using System.Windows.Forms; private DataGrid dataGrid1; // ... dataGrid1.DoubleClick...
|
-
|
If the point is in screen coordinates, then convert it to client coordinates of the DataGrid and use HitTest to find the row and column. using System.Drawing; using System.Windows.Forms; private DataGridCell CellFromPoint( DataGrid dataGrid, Point pointInScreenCoords...
|
-
|
Set the DataGrid's Enabled property to false. Contributed from George Shepherd's Windows Forms FAQ This FAQ item is current to the .NET Framework 1.1 release. Please report status updates here .
|
-
|
You could derive a control from DataGrid and add a SelectedItems property, along the lines of ListView.SelectedItems, like this: using System.Collections; using System.Data; using System.Windows.Forms; public class DataGridSelectedItems : DataGrid { public...
|
-
|
Handle the DataGrid's MouseUp event, and within the hander call the DataGrid.Select method. using System.Drawing; using System.Windows.Forms; private DataGrid dataGrid1; // ... dataGrid1.MouseUp += new MouseEventHandler( dataGrid1_MouseUp ); // ....
|
-
|
Use the DataGrid.Select method. using System.Windows.Forms; DataGrid dataGrid1; // ... dataGrid1.Select( 1 ); // select row 1 Contributed from George Shepherd's Windows Forms FAQ
|
-
|
In an unsorted DataGrid bound to a DataTable, you can get a reference to a row in the DataTable through the DataGrid.CurrentRowIndex. DataTable dataTable = (DataTable) dataGrid1.DataSource; DataRow dataRow = dataTable.Rows[ dataGrid1.CurrentRowIndex ...
|
-
|
The Windows Forms DataGrid does not support the selection of a range of cells other than a group of rows. To select a row, you can click on its row header. But if you want to select a rectangular group of cells, you cannot. To add this support, you can...
|
-
|
You use the row index and column index as indexers on the DataGrid object. private void IterateOverDataTable() { CurrencyManager cm = (CurrencyManager) BindingContext[ dataGrid1.DataSource ]; int rowCount = cm.Count; // assumes data source is a DataTable...
|
-
|
Here is a sample ( C# , VB ) that has column selections implemented. It derives a DataGrid, adds a columns selection array list, and maintains this list in an override of OnMouseDown. Then to handle actually drawing the selected columns, it uses a derived...
|
-
|
You can use the CurrentCell property of the DataGrid. private void button1_Click(object sender, System.EventArgs e) { int colNum = dataGrid1.CurrentCell.ColumnNumber; int rowNum = dataGrid1.CurrentCell.RowNumber; object cellValue = dataGrid1[rowNum, colNum...
|
-
|
You can use the DataGrid's HitTest method, passing it a point in the grid's client coordinate system, and returning a HitTestInfo object that holds all the row and column information that you want. X & Y are in the grid' coordinates. If...
|
-
|
You need to get the DataGridTextBoxColumn.TextBox member, and retrieve the SelectedText from it for the active cell. The sample shows how you can do this as part of handling this TextBox's rightClick. This code assumes you have specifically added...
|
-
|
The sample project DataGridRestrictedInput illustrates how to restrict a column to only accept digits. The technique is general and you can apply it to other kinds of restricted input. Here's the basic idea. You create a custom column style that derives...
|
-
|
using System; using System.Data; using System.Drawing; using System.Windows.Forms; // ... private void dataGrid1_MouseUp(object sender, MouseEventArgs e) { Point point = new Point( e.X, e.Y ); DataGrid.HitTestInfo hti = dataGrid1.HitTest( point ); if...
|
-
|
You can do this by deriving the DataGrid and overriding the OnMouseDown method. In the override, do a HitText and if the hit is on a column header that you do not want to sort, do not call the base class's method. Here is a code that sorts all columns...
|
-
|
The DataGrid class does not have a property that controls whether a new row can be added. But the DataView class does have such an AllowNew property (among others such as AllowEdit and AllowDelete). Here is code that will turn off the append row by getting...
|
-
|
You can use the CurrentCellChanged event to detect when the currentcell changes position. But this event will not allow you to catch the start of a cell being edited. One way you can do this is to catch the TextChanged event in the embedded TextBox within...
|
-
|
This behavior can be seen when you embedded a control like a TextBox or ComboBox in your derived GridColumnStyle. If you press the Tab key slowly, you may see the cell get focus on the KeyDown and the cell lose focus on the KeyUp. One way to avoid this...
|
-
|
One solution is to remove all the editing controls from the DataGrid.Controls collection. Without these controls the grid contents cannot be edited. There is a technical problem that requires a little care. You do not want to delete all the controls in...
|
-
|
One possible solution is that as you move off the cell, you get the typed value, and modify it before it is passed onto the DataGrid for its standard processing. One problem is that there are several ways to leave the cell, and you would want to handle...
|
-
|
To format column output, you do not have to explicitly add DataGridColumns for each column provided you do add a DataGridTableStyle to your DataGrid prior to setting the DataSource property. When you set the DataSource property with a DataGrid that has...
|
-
|
If you make sure your DataGrid is using a DataGridTableStyle, then you can access the TextBox through the GridColumnStyles collection and hook the event there. Here is some code. [C#] //in formload this.dataGrid2.DataSource = this.dataSet11.Customers;...
|
-
|
When you first click into a CheckBox column, the checked state of the cell does not change. One way you can make the checked state change on the first click is to handle the grid's MouseUp event, and change the check value there. [C#] private int...
|
-
|
You can catch clicking off a DataGrid in the DataGrid.Validated event. But this event is also hit when you use the Tab key to move around the grid. So if you want to catch it exclusively for clicking off the grid, you have to ignore the event due to the...
|
-
|
When you select a row in the DataGrid and scroll it out of view using the mouse wheel, you cannot get it back into view. Here is a workaround. dataGrid1.MouseWheel += new MouseEventHandler( dataGrid1_MouseWheel ); // ... private void dataGrid1_MouseWheel...
|
-
|
You can override ProcessCmdKey, catch the Enter key, and swap it for a Tab key by sending a Tab, and not processing the Enter key. public class CustomDataGrid : DataGrid { protected override bool ProcessCmdKey( ref Message msg, Keys keyData ) { if ( msg...
|
-
|
You can handle this by subclassing your grid and overriding either PreProcessMessage or ProcessDialogKey. The code below assumes your datasource is a dataview. If it is not, you could just remove that check [C#] public class CustomDataGrid : DataGrid...
|
-
|
This code adds a method to a derived grid that simulates a mouseclick on the rowheader of the row passed into the method. using System.Runtime.InteropServices; public class CustomDataGrid : DataGrid { public const int WM_LBUTTONDOWN = 513; // 0x0201 public...
|
-
|
There is no event fired when the Boolean value changes. In the attached sample ( C# , VB ), a BoolValueChanged event has been added to a columnstyle derived from DataGridBoolColumn. Catching the changes requires some effort. The strategy is to save the...
|
-
|
You can do this by subclassing your grid and overriding OnMouseMove, and not calling the baseclass if the point is on the columnsizing border. [C#] public class CustomDataGrid : DataGrid { // prevent display of resizing cursor protected override void...
|
-
|
The problem is that the first click of a double click may be caught by the datagrid (and used to activate the cell) while the second click goes to the TextBox for the columnstyle object. This means the TextBox thinks this is a singleclick, and does not...
|
-
|
As you tabbed to the right side of your grid, you tabbed through these zero width column and that is causing the tab key to appear not to work properly. One solution is to handle the grid's CurrentCellChanged event, and if you are on a border cell...
|
-
|
For a single row select DataGrid, you can get both these behaviors by using a custom column style and overriding its Edit method. In your override, handle unselecting and selecting the current row, and DO NOT call the base class. Not calling the base...
|
-
|
There appears to be no method to turn off a currentcell. When a cell is being edited, it is the TextBox embedded in the columnstyle that has the focus, and is displaying the highlighted text. You will notice in this situation, if you click the grid's...
|
-
|
One way to do this is to use a ToolTip control and reset the control text as the mouse moves across cells. Below is a derived DataGrid class that implements this idea. The main points are: Have members that track the current hitRow and hitCol where the...
|
-
|
Override the method ProcessKeyPreview in the DataGrid. protected override bool ProcessKeyPreview( ref Message m ) { Keys keyCode = (Keys) (int) m.WParam & Keys.KeyCode; if ( ( m.Msg == WM_KEYDOWN || m.Msg == WM_KEYUP ) && keyCode == Keys.Enter...
|
-
|
If the column is a boolean column, you can just cast the object returned by the indexer to a bool. bool checked = (bool)dataGridTopics[ row, column ]; Contributed from George Shepherd's Windows Forms FAQ
|
-
|
The DataGrid's CurrentCellChanged event is hit even if you just change cells in the current row. If you want an event that is only hit when you change rows, then you have to look at the binding manager. This object has both a CurrentChanged event...
|
-
|
I want to do custom handling of special keys such as the Tab key or F2 in the TextBox of a column in the DataGrid. How do I subclass this TextBox to get at it virtual members? The TextBox property of the DataGridTextBoxColumn is ReadOnly, so you just...
|
-
|
One way to implement this is to derive a DataGrid and override the virtual OnMouseDown, OnMouseMove and OnMouseUp methods. In your overrides, if the mousedown is on a row header, track the initial mousedown row, and as it moves, draw a line to indicate...
|
-
|
There are problems trying to implement cell by cell validation using the grid's Validating event architecture. The problem is that the grid is not the object handling the data. Instead, a TextBox or some other control is the control managing the changing...
|
-
|
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. You can paste this code in the DataGridDigitsTextBoxColumn sample...
|
-
|
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...
|
-
|
This solution is based off the combobox for datagrid columns found in this FAQ . That solution replaces the standard textbox with a combobox. To get notifications of the changes, a delegate is passed into the constructor for the custom column style. This...
|
-
|
The idea is to create the 'bound' table in your dataset, and then add an extra 'unbound' column. The steps are to derive a custom columnstyle that overrides Paint where you calculate and draw the unbound value. You can also override Edit...
|
-
|
Here is a sample (both VB and C#) that illustrates how to have a parent table which has a related child table, which also has a related grandchild table. Below are some code snippets. The trick is to always make the main parent table be the DataSource...
|
-
|
Take a look at the Microsoft KB article: HOW TO: Extend the Windows Form DataGridTextBoxColumn to Display Data From Other Tables by Using Visual C# .NET (Article ID: 319076) or HOW TO: Extend the Windows Form DataGridTextBoxColumn to Display Data From...
|
-
|
Please download this sample before reading the rest of this FAQ. Looking through the sample will help follow the description. simpledata2.zip What this boils down to is this: 1) Load both Master and Details queries in a dataset. // I am using the SQL...
|
-
|
Here is a technique for binding an ArrayList of objects where the objects contain public properties that should appear as columns in the DataGrid. To bind an ArrayList of these objects to a DataGrid, add a custom DataGridTableStyle that has a MappingName...
|
-
|
Here is a really simple data binding sample. Just drag and drop a DataGrid onto a default Windows Forms application. Follow the steps below to bind this grid to the NorthWind db in SQL server. Complete Sample: simpledata.zip // Create a connection SqlConnection...
|
-
|
Derive a DataGrid. In your derived grid, add a handler for the VertScrollBar.VisibleChanged event. In your handler, if the scrollbar is not visible, size it and position it, and then show it. The code below assumes no horizontal scrollbar is necessary...
|
-
|
If you are using a derived DataGrid, then you can check the Visible property on the protected VertScrollBar property of DataGrid. So, you could check Me.VertScrollBar.Visible from within your derived DataGrid. To check it without access to the protected...
|
-
|
The DataGrid has a protected GridVScrolled member that can be used to scroll the grid. To use it, you can derive from DataGrid and add a ScrollToRow method. Here is a code snippet. Public Class MyDataGrid Inherits DataGrid Sub ScrollToRow(ByVal row As...
|
-
|
You create a custom DataTableStyle that contains column styles for each column you want to display. You 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...
|
-
|
You need to derive a custom column style, override its Paint method and draw the image. In the attached samples, ( VB and C# ), there are two custom column styles. One style is a stand-alone unbound column that just displays an image. The second custom...
|
-
|
If you have added a table style to your DataGrid (so individual column styles have been generated), then you can use code such as this to set the Format property of the particular column style. [C#] // add format column 3 columnstyle where column 3 holds...
|
-
|
The idea is to load your datatable in a normal fashion. Once the datatable is loaded, you can add an additional column that is computed from the other columns in your datatable. In the sample ( CS , VB ), we load the CustomerID, CompanyName, ContactName...
|
-
|
You can derive a custom columnstyle and override its Paint method to draw the image. Here are both C# and VB.Net samples . The Paint override offers three ways to draw the bimap in the cell; size it to fit the cell bounds, size it proportionally to fit...
|
-
|
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...
|
-
|
This sample ( download C# , download VB ) derives two custom columnstyles that display buttons. One displays a pushbutton with the cell text used as the button label. The second columnstyle displays text plus a dropdown button similar to a combobox button...
|
-
|
If you have added a TableStyle for your grid, then the code below should set the right column width to be the empty space from a button click. If you need to dynamically do this in response to the user sizing other columns, then there may be more work...
|
-
|
One way to do this is to use MeasureString to compute the size of the text in each cell, and then take the maximum value. Below is a code snippet that does this. It assumes your datagrid is bound to a datatable. You can download a full working sample...
|
-
|
You can control the columns displayed in the DataGrid through the DataGrid.TableStyle[0].GridColumnStyles collection. To do so, create a DataGridTableStyle and set its MappingName property to point to the name of your DataTable which is the DataSource...
|
-
|
DataGrid does not expose row height through a public member. However it is possible to set row heights using reflection to access the DataGrid internal row properties, based on a suggestion from Matthew Benedict. Here is a sample project (C# and VB) showing...
|
-
|
If you add a DataGridTableStyle to your DataGrid, then you can use the ColWidth property of the GridColumnStyles to set the width of each column. To dynamically set these widths as the grid is resized, you can handle the SizeChanged event of the DataGrid...
|
-
|
To set a column width, your DataGrid must be using a non-null DataGridTableStyle. Once this is in place, you can set the column width by first getting the tablestyle and then using that object to obtain a column style with which you can set the width...
|
-
|
There are several ways to hide a column: 1) You can use your DataSet's ColumnMapping property to hide a column. // Creating connection and command sting string conStr = @"Provider=Microsoft.JET.OLEDB.4.0;data source=C:\northwind.mdb"; string...
|
-
|
Here is a solution suggested by Matthew Benedict. It uses reflection to access the protected DataGridRows collection so he can set the row height. public void AutoSizeGrid() { // DataGrid should be bound to a DataTable for this part to // work. int numRows...
|
-
|
You can get at the width and visibility of the header row/column through a DataGridTableStyle. DataGridTableStyle has properties such as RowHeadersVisible and RowHeadersWidth. DataGridTableStyle also controls things like selections colors and GridLine...
|
-
|
There is no text property exposed for a rowheader cell. But you can handle the Paint event and draw header text yourself. You can download sample projects ( C# , VB ) that illustrate one technique for doing so. The sample loads the DataGrid in the form's...
|
-
|
Set the DataGrid.AllowNavigation property to false. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Here is a VB and C# sample showing how you might do this. The idea is to add TextBoxes and Lables to a Panel with whatever layout you want to use. Then use DataBindings.Add calls to bind the TextBoxes to columns in your grid's datasource. Then, since...
|
-
|
When the user adds a new row in a DataGrid, the columns display "(null)". To prevent this behavior and make all the columns be empty, you can set the DefaultValue property of the DataColumn to be String.Empty. Contributed from George Shepherd's...
|
-
|
You use the DataColumn.DefaultValue property to provide default values for new rows. You access this property through the DataTable associated with the DataGrid, [C#] dataGrid1.DataSource = dataSet.Tables[ "orders" ]; // default value for column...
|
-
|
One way you can do this is to derive a class from DataGrid and override its WndProc method to handle the WM_SETCURSOR method. In your override, you can do hit testing to decide when you want to set the cursor, or when you want to call the base class and...
|
-
|
One way to do this is to use a derived columnstyle, override the Paint method and do the text drawing yourself, using whatever font or colors you like. If you add an event to your derived column style that is fired immediately before the text is drawn...
|
-
|
You can use the first technique listed in this FAQ: How do I color an individual cell depending upon its value or some external method? The idea is to derive a custom columnstyle. override its Paint method to specially color the background of the currentcell...
|
-
|
Take a look at this Microsoft KB article, HOW TO: Extend the Windows Form DataGridTextBoxColumn Control to Custom-Format Data (Q318581) . It subclasses a DataGridColumnStyle and overrides both GetColumnValueAtRow and Commit to implement this behavior...
|
-
|
DataTable dt = (DataTable) dataGrid1.DataSource; foreach ( DataRow row in dt.GetErrors() ) { row.RowError = string.Empty; foreach ( DataColumn col in dt.Columns ) row.SetColumnError( col, string.Empty ); } Adam Chester
|
-
|
In a Windows Forms DataGrid, there is no property exposed that gives you this information. But here is little trick that will allow you to get the top-left visible cell. 1) Add a private member Point pointInCell00 to the form containing the DataGrid....
|
-
|
One way you can do this is through the BindingManager.Count property. [C#] int numRows = dataGrid1.BindingContext[ dataGrid1.DataSource, dataGrid1.DataMember ].Count; Contributed from George Shepherd's Windows Forms FAQ
|
-
|
We 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...
|
-
|
If your datagrid does not have a custom TableStyle associated with it, then there are two DataGrid properties that control the color and visibility of the gridlines. DataGrid..GridLineColor DataGrid.GridLineStyle If you have a custom TableStyle. you need...
|
-
|
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...
|