Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

Browse by Tags

All Tags » Using Controls (RSS)


  • How can I bind a list of items to entries in a ToolStripDropDown?

    Several people have asked on the newsgroups about a good method to bind a list of items to entries in a ToolStripDropDown instance. I've run into this issue a couple of times and wanted to share some sample code. The class takes in a ToolStripDropDown...
  • How can I reset the settings?

    The sample code below will do that – it simply uses a named set of settings that captures the state before any custom settings are applied. Then, with button click or whatever you can apply the custom set. private void Form1_Load(object sender, EventArgs...
  • How do I programatically move ToolStrips within or across ToolStripPanels?

    Within a ToolStrip: Simply set the ToolStrip Location property. Across ToolStrips: Either add the ToolStrip to the ToolStripPanel's Controls collection or use Join(ToolStrip). NOTE: Join() simulates the drop operation of a ToolStrip and is order dependent...
  • How can I use the ToolStripPanel with MDI applications?

    The following is how to use ToolStripPanels correctly in an MDIParent. This is important, because due to layering and MDI limiations, use of ToolStripContainer doesn't work well. public Form1() { // Make Form MDI Parent this.IsMdiContainer = true;...
  • Why does the ToolStripContainer not support MDI?

    ToolStripContainer does not support MDI properly because, like any dock filled container, it would be layered above the MDI child container that is part of the MDI parent. To workaround this, use ToolStripPanel – see that section for a code example.
  • What is the ToolStripContainer?

    ToolStrip container is a composite control very similar in overall design to the SplitContainer. It takes four ToolStripPanels docked to the sides and one ContentPanel dock filled in the middle to make up the typical four sided arrangment commonly used...
  • How can I disable Visual Styles?

    The System Renderer renders ToolStrips similar to Win32 look and feel. You can use with or without VisualStyles by ToolStripManager.VisualStylesEnabled = false;
  • How can I get the Office look and feel to have straight ends?

    Set RoundedEdges = false. You may also have to override OnRendererToolStripBorder and not call base. ((ToolStripProfessionalRenderer)ToolStripManager.Renderer).RoundedEdges = false;
  • How can I change text color on selection?

    Below is an example of changing text color on selection within a custom renderer: protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { if (e.Item.Selected) { e.TextColor = Color.Gold; } else { e.Item.ForeColor = Color.White;...
  • What is the ConnectedArea?

    Connected area is that little bit of the dropdown for a menu where the border is discontinuous. Below is an examples of how to access and paint that. protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { using (Brush b = new SolidBrush...
  • How do I change the ProfessionalColorTable?

    Override ProfessionalColorTable and change only the colors you care about. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load Dim t As MyColorTable = New MyColorTable ToolStrip1.Renderer = New ToolStripProfessionalRenderer...
  • What order do the ToolStrip Renderer events come in?

    Generally its this - background, item background, item foregound effects, toolstrip border. OnRenderToolStripBackground OnRender[Label|Button|MenuItem...]Background OnRenderItemText OnRenderItemArrow OnRenderItemImage OnRenderToolStripBorder The toolstrip...
  • When should I use a renderer and when should I just override OnPaint

    Use draw from custom ToolStrip handler – which is the entry point into Renderer code. OnRender* will be called as a result. To change Renderer behavior, override OnRender*. public class MyLabel : ToolStripLabel{ protected override void OnPaint(PaintEventArgs...
  • Can I make the ProfessionalRenderer look like the old Office?

    Yes... Create a class which overrides the ToolStripProfessionalRenderer called OldProfessionalRenderer Pass in a new ProfessionalColorTable with professionalColorTable.UseSystemColors = false; In the OldProfessionalRenderer class, override the following...
  • How do I turn off the "Office" colors?

    For one ToolStrip ProfessionalColorTable colorTable = new ProfessionalColorTable(); colorTable.UseSystemColors = true; toolStrip.Renderer = new ToolStripProfessionalRenderer(colorTable); For the entire app: ToolStripManager.VisualStylesEnabled = false;
  • How do I globally change the painting (Renderer) for all my ToolStrips?

    Use RenderMode to pick between stock renderers. Use ToolStrip.Renderer to assign a custom renderer. Ensure that RenderMode == ManagerRenderMode (default) class Form6 : Form { ComboBox targetComboBox = new ComboBox(); public Form6() { // alter renderer...
  • How do Settings work with the ToolStripManager?

    Settings are another feature handled in ToolStripManager. This uses the settings engine to automatically persist and restore the entire ToolStrip tree. This allows you to enable drag to dock scenarios in the ToolStripPanel and AllowItemReorder without...
  • Do you have a sample with the other MergeActions?

    See http://blogs.msdn.com/jfoscoding/articles/472113.aspx
  • How do get items to merge into the middle of a menu, in the right order AND

    There are several factors that contribute to the being a bit tricky. One is the fact that MergeIndex is ignored when MergeAction = Append. The second is the live nature of the merge; incoming items affect the index. To accomplish this, order the items...
  • What does MatchOnly do?

    A MergeAction of MatchOnly simply provides a mechanism to navigate through the menu structure without taking any true action. In a way it provides a path to evaluate the subsequent items.
  • Why is there an empty MenuStrip in my child MDI forms?

    The MenuStrip is visible=true and even though it is empty, we render it. Simply set Visible=false to fix this.
  • How does Merging work with the ToolStripManager?

    ToolStripMerging is driven through two different mechanisms: Automatic (MDI) and manual. This section covers top level concepts in both of the mechanisms. The rules of how the items merge do not change for these two methods, just the triggering mechanism...
  • What is the ToolStripManager?

    ToolStripManager is a static class that handles application wide ToolStrip related tasks such as merging, settings and renderer exposure.
  • How can I use a ToolStripDropDown as a Tree-View dropdown?

    This is a rather spiffy article: http://blogs.msdn.com/jfoscoding/archive/2005/03/03/384430.aspx
  • How can I make a user resizable dropdown?

    Handle WM_NCHITTEST. See http://blogs.msdn.com/jfoscoding/archive/2005/04/20/410231.aspx for more detail.
  • How can I control DropDownDirection?

    DropDownDirection is controlled via two different mechanisms. One is DefaultDropDownDirection offered on ToolStrip, the other is an argument to the Show() method on ToolStripDropDownMenu. TooStrip.DropDownDirection This controls the default direction...
  • How do I dynamically populate a dropdown in the Opening event?

    public partial class Form1 : Form { ContextMenuStrip MyContextMenuStrip = new ContextMenuStrip(); bool CloseClicked = false; public Form1() { InitializeComponent(); // add close item, name it MyContextMenuStrip.Items.Add("Close"); // add separator...
  • How do I prevent a dropdown from closing?

    Two ways, set AutoClose = false, or handle the Closing event and set e.Cancel = true. The Closing event should give you a reason - if you want to prevent the dropdown from being closed when a specific item is clicked - sync the Opening event, hold onto...
  • How can I use the ContextMenuStrip?

    class Form3 : Form { private ContextMenuStrip fruitContextMenuStrip; public Form3() { // new ContextMenuStrip fruitContextMenuStrip = new ContextMenuStrip(); // sync opening event fruitContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler...
  • What is the ContextMenuStrip?

    ContextMenuStrip is the ToolStrip version of ContextMenu. It can be associated with any control and a via secondary click will automatically show. It can also be shown programmatically via the Show() API. It supports an Opening and Closing cancellable...
  • Can I show animated images in ToolStrips?

    Yes. ToolStrip supports the ImageAnimator class - if you assign an Animated GIF to the Image property it will automatically render the animation.
  • How does Spring work with StatusStrips?

    Spring is supported only in StatusStrip and only with StatusStripLabels. It utilizes the underlying Table layout with a columnstyle set to percentage to achieve the effect of the Spring panel filling the remaining space. Multiple ToolStripPanels set to...
  • How can I get an item aligned to the right?

    By default, the StatusStrip is not set to LayoutStyle.StackWithOverfow, therefore the item.Alignment property is ignored. To align an progress bar to the right, use a ToolStripStatusLabel – set it's Spring = true, then add a ToolStripProgressBar....
  • What is the StatusStrip?

    StatusStrip replaces the StatusBar control. Special features of the StatusBar is a custom Table Layout, support for the form's sizing grip and Spring.
  • How does the MenuStrip work with MDI applications?

    The MDI related features around MenuStrip are described below. Using a MenuStrip in MDI requires Form.MainMenuStrip to be set in order to identiy the controlling MenuStrip. It will be used for child window control menu merging when children are maximized...
  • What is the MenuStrip?

    MenuStrip is the ToolStrip family of control's replacement for MainMenu. It also handles the majority of key handling in the menu activation case and has special logic around Form.MainMenuStrip. There are special MDI features around MDIWindowListItem...
  • How does Overflow work with the ToolStrip?

    To be precise, overflow is a feature of the ToolStrip's default LayoutStyle (StackWithOverflow), not of the ToolStrip control itself. You determine what overflow action is preferred via the Overflow property (Always, Never, AsNeeded). To determine...
  • How can I synchronize a ToolStripSplitButton's item with the selection?

    ToolStripSplitButton.DefaultItem is an easy mechanism to synchronize the click event from the ToolStripSplitButton's item chosen from the dropdown with the one rendered in the button area. This sample assumes you have a click handler associated with...
  • How can I populate a ToolStripDropDownItem?

    ToolStripDropDownItem is the abstract base class for ToolStripMenuItem, ToolStripDropDownButton, ToolStripSplitButton and provides the API around populating and synching the dropdown and items within it. This class implements all the dropdown plumbing...
  • How can I add a User Control to a ToolStrip?

    ToolStripControlHost is the base class for our ToolStripTextBox, ToolStripComboBox, ToolStripProgressBar, and can wrap any user control to be hosted in the ToolStrip. There are multiple ways to use ToolStripControlHost:: Inherit from ToolStripControlHost...
  • Do ToolStrips automatically eliminate duplicate or trailing separators from layout?

    No, but the following code will do it for you: void DropDown_Layout(object sender, LayoutEventArgs e) { StripSeparators(((ToolStrip)sender).Items); } public void StripSeparators(ToolStripItemCollection tsItems) { // ItemCollections should neither begin...
  • What's an easier way to enter a separator than newing one up or picking from the dropdown?

    Simply enter a hyphen or dash("-") in either the designer template node or via the Add method on ToolStripItemCollection. This will automatically create a separator.
  • How do I get toggle button?

    toolStripButton.CheckOnClick = true; toolStripButton.CheckedChanged += new EventHandler(toolStripButton_CheckedChanged);
  • Do ToolStrips support a link control?

    Yes, ToolStripLabel has an IsLink property that will render it in a link style. LinkColor, LinkVisited and LinkBehavior are exposed.
  • How do I get a mnemonic for a ToolStripComboBox, ToolStripTextBox or similar?

    ToolStripLabel supports mnemonic forwarding – simply precede your ToolStripControlHostItem with a ToolStripLabel with a mnemonic defined and you will get focus to the ToolStripControlHostItem when ALT+mnemonic is pressed.
  • How can I clone a ToolStripMenuItem?

    By default, ToolStripMenuItem does not contain an implementation for clone. Here's the code for ToolStripMenuItem.Clone. An alternate solution is to implement IBindableComponent and databind your menu item to a Command which drives the Text/Image...
  • How can I tell when the mouse is over a  ToolStripButton?

    Use the Selected property for items in which "CanSelect" is true. Otherwise you'll have to sync MouseEnter, MouseLeave events. You can check for Selected in your custom Renderer as well.
  • How do I change layout characteristics not dircectly exposed in ToolStrip?

    You access the LayoutSettings object offered at the ToolStripLevel and cast to the appropriate type and access the properties there. The following is an example of changing the flow direction of a ToolStrip. toolStrip1.LayoutStyle = ToolStripLayoutStyle...
  • How does the ToolStrip Layout work?

    By default the ToolStrip control utilizes a StackWithOverflow layout that supports overflow and item alignment. Stack refers to how the items are laid out within the ToolStrip, each item stacked aside each other at both ends of the ToolStrip. ToolStripLayoutStyle...
  • How can I add a customization dialog like the one in Office?

    A common customer request we get is a dialog similar to Office's to handle end user customization to choose items. We don't include this in the product. However, we do have a great sample on this already created, and the API around ToolStrips...
  • How can I customize the ToolStripItems at design-time?

    The two avenues of customization covered here are custom ToolStripItems at design time and custom renderer custom ToolStrips at design time. Custom ToolStripItems Custom ToolStripItems can be created by extending existing ToolStripItems like ToolStripButton...
  • How do I get one image out of many to not be scaled?

    Use ToolStripItem.ImageScaling = ToolStrimItemImageScaling.None
  • How does image scaling work with ToolStrips?

    Image scaling is determined by the interaction of several properties. size ToolStrip.ImageScalingSize This is a the size that will be used to scale into as determined by the Item's ImageScaling and the container's AutoSize setting ToolStripItemImageScaling...
  • How do property values flow from parent to auto created dropdowns?

    For the implementation of faux-ambient properties we make a distinction in how the dropdown for a ToolStripDropDownItem is created. We automatically flow Font, ImageScalingSize and Renderer to the autocreated dropdown. In the case of explicitly created...
  • How can I tab out of a ToolStrip? It just starts over from the first item again and again.

    In this case, the ToolStrip will accept the first tab to tab in - and the arrow keys will do wrapping selection. The second tab will tab you to the next control. Commonly used when not contained within a ToolStripPanel. toolStrip.TabStop = true;
  • How do Mnemonics work with ToolStrips?

    Combined with or following the ALT key, mnemonics are one way to activate a ToolStripItem via keyboard. ToolStrip supports both explicit and implicit mnemonics. Explicit mnemonics are defined inline with the ampersand (&) character preceding the letter...
  • How does ToolStrip usage affect Tab order?

    Toolstrips have three main usage patterns that impact how they are laid out, keyboard interaction and end-user behavior. Joined in a ToolStripPanel This means that the ToolStrip is typically repositionable within the ToolStripPanel and across ToolStripPanels...
  • Why are ToolStrips limited under Partial Trust?

    The limitations of ToolStrips under partial trust are designed primarily to prevent spoofing attacks. Spoofing attacks consist of some fake dialog or familiar window that lures the user into entering personal information. The two elements are a full fidelity...
  • How does parenting work with ToolStrip controls?

    The concept of container ownership and parenting is more complex in ToolStrips than in a typical Windows Forms container control. That is necessary to support dynamic scenarios such as overflow, sharing drop downs across multiple ToolStrip items and to...
  • Do I need to worry about double buffering?

    By default the ToolStrip is double buffered; taking advantage of the OptimizedDoubleBuffer API offered in Windows Forms 2.0.
  • When should I use Paint/OnPaint and when should I override the ToolStripRenderer?

    If you want to tweak a few aspects of how an item is painted, overriding the ToolStripRenderer might be the right idea. If you are writing a new item and want to control all aspects of the painting, overriding OnPaint will give you total control. From...
  • How can I customize the painting of ToolStrip controls?

    There are several ways to achieve custom painting with the ToolStrip API. As with other System.Windows.Forms.Controls, the ToolStrip and ToolStripItem both have overridable OnPaint methods and Paint events. As with regular painting, the coordinate system...
  • How can I vertically-align autosizing buttons?

    Here is the scenario: Simply setting Button.AutoSize=true on each button will break your alignment, since the localized strings are likely to be different lengths - so you'd get this: The solution is to place the three (or however many) buttons (or...
  • How Do I turn off scaling for one control?

    For user control AutoScaleMode applies to the contents of the container – that way controls within a form can be repositioned and scaled according the Form level AutoScaleMode and the user control contents are scaled according to the user control level...
  • How does AutoScale affect control positioning?

    AutoScale refers in general to recalculating sizes and positions for controls without reliance on an outer layout container or engine doing the calculation. This is done for environment changes like font, DPI etc. For 1.1 the default code spit was : this...
  • What are some AutoSize considerations with LayoutEngines?

    The LayoutEngine iterates through all child controls and asks each control for its preferred size via GetPreferredSize when AutoSize = true. Each layout engine is free to do what it wants with this information. Dock layout Left, Right - controls size...
  • How can I create a sizable autosized form?

    If you set AutoSize = true for a form, the default setting for AutoSizeMode is GrowOnly. This means an AutoSized dialog in this mode cannot snap back down to a smaller size. Typically this is not what you want. If you want a resizable dialog that can...
  • How do controls behave with GetPreferredSize?

    Control Had AutoSize in Everett AutoSize by default * Shrinks in Anchor+ Implementation details Could be Affected by... Button No No No Forwards to ButtonBase - applies a minimum size of Button.DefaultSize, unless its a FlatStyle.System, in which case...
  • How can I debugging FlowLayoutPanel?

    Want to know when a control's size is set to X,Y? Put a conditional breakpoint in Control.cs SetBoundsCore. http://blogs.msdn.com/jfoscoding/archive/2005/09/05/461096.aspx
  • What direction do controls grow when they AutoSize?

    Controls "grow" (expand) opposite their anchors - so a button anchored Bottom, Right would grow leftwards if its string grew, and upwards if its font grew.
  • What are all the size properties for FlowLayoutPanel?

    MinimumSize : the bare minimum size a control can be set to MaximumSize : the maximum size a control can be set to PreferredSize : the size a control prefers to be - this is implemented by calling GetPreferredSize(0,0) AutoSize : Boolean specifying whether...
  • What is FlowBreak?

    You can set FlowBreak on the control which is the last of that row/column. The following control should appear in the next column/row.
  • How can I get the items in a flow layout panel to flow TopDown and stretch from edge to edge?

    The sample essentially sizes an item to hold the width to a certain size. private void fLP1_Layout(object sender, LayoutEventArgs e) { fLP1.Controls[0].Dock = DockStyle.None; for (int i = 1; i < fLP1.Controls.Count; i++) { fLP1.Controls[i].Dock = DockStyle...
  • How do I position controls with FlowLayoutPanel?

    Currently, the implementation of Anchoring and Docking with FLP, as illustrated in the picture below, is that a control is "box stretched" only as far as the extent of the longest/tallest control in the FLP. Dock and Anchor – control how an...
  • How do I add a control to a FlowLayoutPanel?

    You simply add to the controls collection, but unlike the TLP, you can't specify row and column – the controls are laid out in natural order from the collection. To move the controls, alter the position within the collection for that control.
  • What is FlowLayoutPanel?

    Flowlayout panel is a much simpler control than TableLayoutPanel. It arranges items as a linear collection, supporting wrapping. It works well for menuing and list like scenarios and also supports textwrapping and some interesting alignment options. FlowLayoutPanel...
  • What are the the techniques for text wrapping?

    Wrapping radio button/checkbox http://blogs.msdn.com/jfoscoding/articles/478300.aspx Wrapping text http://blogs.msdn.com/jfoscoding/articles/478299.aspx
  • How can I use TableLayoutPanel for resizable dialogs?

    Resizable dialogs require that controls are present that the user may want to resize to better use. In general, items such as labels and buttons will not need to be modified by the user. They will be covered by auto-layout. Controls that do need to be...
  • How can I use TableLayoutPanel with non-resizable dialogs?

    Dialogs with a fixed border are generally the easiest to set up auto-layout for. They should have an overarching TLP with AutoSize set to true and AutoSizeMode set to GrowAndShrink. The Form it is on should be set to AutoSize = true with an AutoSizeMode...
  • How can I layout group boxes with TableLayoutPanel?

    Group boxes tend to have similar behavior to dialogs except that they contain fewer controls. Also, many group boxes will be required to grow vertically with font changes and still stretch with the form. The below example has a TableLayoutPanel inside...
  • What are some Autolayout considerations for textbox button combinations?

    Every scenario differs a bit, but a TableLayoutPanel can often address this issue. For instance, if you have the following arrangement: Simple setting the button to AutoSize (assuming the button is anchored Top, Left) would "push" the form bigger...
  • How can I maintain equal sizing amongst horizontally-aligned autosizing buttons?

    Here is the scenario: Simply setting Button.AutoSize=true would cause the buttons to have unequal size, ala: Instead, place the controls within a TableLayoutPanel One row and three columns for this example Set each column to equal percentage column style...
  • How do Extender-provider properties work with TableLayoutPanel?

    Rather than have properties on Cells, the table layout panel proffers properties on the controls within the cells via extender providers. Below is the list of those offered. CellPosition public void SetCellPosition (Control control, TableLayoutPanelCellPosition...
  • How are Rows and Columns generated?

    Whereas the getter for RowCount / ColumnCount returns the number of rows or columns in the table layout panel respectively, the setter is peculiar in that it sets the minimum number of rows or columns to create. This is throttled by the surprisingly well...
  • How do ColumnStyles and RowStyles work with TableLayoutPanel?

    The ColumnStyles and RowStyles collection control the sizing of all the rows and columns. If these are empty or there are more rows/columns than styles, it is assumed the column/row is "AutoSized". AutoSize – sizes the column/row to the minimum...
  • How can I position Controls with TableLayoutPanel?

    Additionally the tableLayoutPanel provides several methods to change the position of controls that are already added to the table: tableLayoutPanel.SetCellPosition(new TableLayoutPanelCellPosition(4,2)) NOTE: Via extender provider on the control itself...
  • How can I add Controls to a TableLayoutPanel?

    Controls can be added to the TableLayoutPanel in a free-styled manner via the Add method on the Controls collection. The newly added control will be added in the next available cell, but generally column and row positions are assigned to the child controls...
  • So I should use TableLayoutPanel everywhere, right?

    No - TableLayoutPanel is very powerful, but was designed to provide a very specific set of functionality. It is tempting to try to use it in all new Whidbey forms, but this generally leads to sadness and misery, specifically in the form of shoddy UI performance...
  • What is the TableLayoutPanel?

    Our primary weapon in our auto-layout arsenal is the Table Layout Panel (TLP). TLPs act similar to HTML tables in their ability to regulate space and flow on a form. The TableLayoutPanel has several key sources of information that it uses to determine...
  • Why is my ComboBox slow to load when data binding?

    ComboBox loading performance issues are generally related to loading the data multiple times. The two most common scenarios for this are setting the DisplayMember after setting the DataSource or binding the ComboBox prior to filling the DataSource. Setting...
  • How can I get the ComboBox to display multiple data source properties?

    ComboBox binding does not directly support data source property concatenation however you can use the ComboBox Format event to concatenate multiple data source properties. Sample: Concatenating data source properties using the Format event (VS 2005) ...
  • How can I add a "null" or "DBNull" entry to my bound ComboBox?

    When data bound, the Windows Forms ComboBox does not provide a general way to add a "null" or "not selected" value to its items list. The only generally supported way to do this is to add a "null" item to your data source...
  • How do I setup a ComboBox to bind to a Lookup table?

    A common use of a ComboBox in a data bound application is as a lookup based UI control. From a database perspective, a Lookup control is used to provide the "lookup" values for a foreign key. For example, assume you have a customer table with...
  • What are the DisplayMember and ValueMember?

    You can fill a ComboBox with non-string items such as business objects. By default, the ComboBox will call ToString() on each of the items to generate the display text (visible text). Rather than rely on ToString(), you can have the ComboBox use one of...
  • How do I display a confirmation dialog when the user tries to delete a row?

    When the user selects a row in the DataGridView and hits the delete key, the UserDeletingRow event fires. You can prompt the user if they want to continue deleting the row. It is recommended that you only do this if the row being deleted is not the new...
  • How do I commit the data to the database when clicking on a toolstrip button?

    By default, toolbars and menus do not force validation for controls. Validation is a required part of validating and updating the data in a bound control. Once the form and all bound controls are validated, any current edits need to be committed. Finally...
  • How do I prevent sorting?

    By setting the DataGridViewColumn.SortMode property you can disable the ability for the user to sort on the given column. You can use Visual Studio 2005 to set this property by right-clicking on the DataGridView and choosing the Edit Columns option. Next...
  • How do I show master-details in the same DataGridView?

    The DataGridView does not provide any support for showing master-details data in the same DataGridView. The previously shipped Windows Forms DataGrid control can be a solution if this is something that you need.
  • How do I show master-details?

    One of the most common scenarios for using the DataGridView control is the master/detail form, in which a parent/child relationship between two database tables is displayed. Selecting rows in the master table causes the detail table to update with the...
  • How do I show data that comes from two tables?

    The DataGridView does not provide any new features apart from virtual mode to enable this. What you can do is use the JoinView class described in the following article http://support.microsoft.com/default.aspx?scid=kb;en-us;325682 . Using this class you...
  • How do I show unbound data along with bound data?

    The data you display in the DataGridView control will normally come from a data source of some kind, but you might want to display a column of data that does not come from the data source. This kind of column is called an unbound column. Unbound columns...
  • How do I show the error icon when the user is editing the cell?

    Sometimes when using the error text and icon feature you want an immediate feedback to the user that something that they typed into a cell is incorrect. By default when setting the ErrorText property the error icon will not appear if the cell is in edit...
  • How do I have a combo box column display a sub set of data based upon the value of a different combo box column?

    Sometimes data that you want to display in the DataGridView has a relationship between two tables such as a category and subcategory. You want to let the user select the category and then choose between a subcategory based upon the category. This is possible...
  • How do I enable typing in the combo box cell?

    By default a DataGridViewComboBoxCell does not support typing into the cell. There are reasons though that typing into the combo box works well for your application. To enable this, two things have to be done. First the DropDownStyle property of the ComboBox...
  • How do I make the image column not show any images?

    By default the image column and cell convert null values to the standard "X" image. You can make no image show up by changing the column's NullValue property to null. The following code example sets the NullValue for an image column: this...
  • How do I have the cell text wrap?

    By default, text in a DataGridViewTextBoxCell does not wrap. This can be controlled via the WrapMode property on the cell style (e.g. DataGridView.DefaultCellStyle.WrapMode). Set the WrapMode property of a DataGridViewCellStyle to one of the DataGridViewTriState...
  • How do I make the last column wide enough to occupy all the remaining client area of the grid?

    By setting the AutoSizeMode for the last column to Fill the column will size itself to fill in the remaining client area of the grid. Optionally you can set the last column's MinimumWidth if you want to keep the column from sizing too small.
  • How do I perform drag and drop reorder of rows?

    Drag and dropping to reorder rows is not built into the DataGridView, but following standard drag and drop code you can easily add this functionality to the DataGridView. The code fragment below shows how you can accomplish this. It assumes that you have...
  • How do I handle the SelectedIndexChanged event?

    Sometimes it is helpful to know when a user has selected an item in the ComboBox editing control. With a ComboBox on your form you would normally handle the SelectedIndexChanged event. With the DataGridViewComboBox you can do the same thing by using the...
  • When should I remove event handlers from the editing control?

    If you hook up an event handler on your editing control that is temporary (maybe for a specific cell in a specific column) you can remove the event handler in the CellEndEdit event. You can also remove any existing event handlers before adding an event...
  • How do I hook up events on the editing control?

    Sometimes you will need to handle specific events provided by the editing control for a cell. You can do this by first handling the DataGridView.EditingControlShowing event. Next access the DataGridViewEditingControlShowingEventArgs.Control property to...
  • How do I sort on multiple columns?

    By default the DataGridView control does not provide sorting on multiple columns. Depending upon if the DataGridView is databound or not, you can provide additional support for sorting on multiple columns. Databound DataGridView When the DataGridView...
  • How do I prevent the user from sorting on a column?

    In the DataGridView control, text box columns use automatic sorting by default, while other column types are not sorted automatically. Sometimes you will want to override these defaults. In the DataGridView control, the SortMode property value of a column...
  • How do I hide a column?

    Sometimes you will want to display only some of the columns that are available in a DataGridView. For example, you might want to show an employee salary column to users with management credentials while hiding it from other users. To hide a column programmatically...
  • Why does the cell text show up with "square" characters where they should be new lines?

    By default, text in a DataGridViewTextBoxCell does not wrap. This can be controlled via the WrapMode property on the cell style (e.g. DataGridView.DefaultCellStyle.WrapMode). Because text doesn't wrap, new line characters in the text do not apply...
  • How do I show controls in all cells regardless of edit?

    The DataGridView control only supports displaying an actual control when a cell is in edit mode. The DataGridView control is not designed to display multiple controls or repeat a set of controls per row. The DataGridView control draws a representation...
  • How do I restrict user from setting focus to a specific cell?

    By default the DataGridView's navigation model does not have any ability to restrict focus to a specific cell. You can implement your own navigation logic by overriding the appropriate keyboard, navigation and mouse methods such as DataGridView.OnKeyDown...
  • How do I disable a cell?

    While a cell can be read-only to prevent it from being editable, the DataGridView does not have built-in support for disabling a cell. Normally the concept of "disabled" means that the user cannot navigate to it and usually has a visual cue...
  • How do I prevent a particular cell from being editable?

    The ReadOnly property indicates whether the data displayed by the cell can be edited. You can set ReadOnly for individual cells, or you can make an entire row or column of cells read-only by setting the DataGridViewRow.ReadOnly or DataGridViewColumn.ReadOnly...
  • What if I want to add masking to other text controls?

    The MaskedTextProvider class encapsulates the mask engine functionality used by the MaskedTextBox. This class can be used to provide masking to other text entry controls. For more information, see http://msdn2.microsoft.com/en-us/library/yfth38zd
  • How can I get a masked text column in the DataGridView?

    There is an sample that shows this. You can download it from: http://winfx.msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_fxsamples/html/ba7b4105-e562-4a4b-8890-485c8f855c69.asp
  • How can I create a custom mask type that shows up in the Mask picker dialog in Visual Studio?

    You need to create a class that inherits from MaskDescriptor. Also, if you want Type validation support, you'll need to implement a public static Parse method that takes a string. The MaskedTextBox sample app in the SDK shows this. See the IPv5 and...
  • How can I access the pre-defined masks from other cultures?

    When you change the Culture property on the MaskedTextBox, the Mask picker dialog will show the pre-defined masks for that culture.
  • How can I tell if the MaskedTextBox is in insert mode?

    The IsOverwriteMode property will return true if characters entered will overwrite existing characters. This property combines the value of the InsertKeyMode property with the current setting of the insert key to produce the value.
  • How do I make the MaskedTextBox always overwrite like in Access?

    Set the InsertKeyMode property to InsertKeyMode.Overwrite. The default value of this property is InsertKeyMode.Default which honors the state of the insert key on the keyboard.
  • How can I use the MaskedTextBox to tell if a date is between a certain range?

    Use the MaskedTextBox's TypeValidationCompleted event. This event occurs when the MaskedTextBox loses focus and the static Parse method on the Type set into the ValidatingType proeprty is called. The IsValidInput property on the TypeValidationEventArgs...
  • How do I data bind to a MaskedTextBox?

    Set up a binding to the Text property and then set a mask that will match your data's constraints. If there are optional characters in the data, you'll need to setup the FormatString on the Text's Binding object to always fill out those optional...
  • What is the mask language?

    For more information, see http://msdn2.microsoft.com/en-us/library/wdt8exfc Masking element Description 0 Digit, required. This element will accept any single digit between 0 and 9. 9 Digit or space, optional. # Digit or space, optional. If this position...
  • How can I make the SplitContainer continuously update its contents while the splitter is moving?

    Note: Continuously updating a SplitContainer's contents can lead to poor performance, and should be used sparingly. By default, when moving a SplitContainer's splitter a preview is shown of the splitter's future location. Then when the splitter...
  • How can I prevent the SplitContainer from stealing focus?

    The default behavior for the splitter is to take focus once selected. If you want the splitter to be movable without taking focus you can do one of two things: Use the custom control defined in the SplitContainerNoFocus sample Insert the following code...
  • Why isn't the splitter visible when I run my application?

    If the splitter is not distinguishable from the rest of the split container, it is due to the SplitContainerPanels having the same background color as the splitter, and the BorderStyle being set to None. To make the splitter easily recognizable, change...
  • How do I select the SplitContainer at design time?

    If you want to select a SplitContainer control at design time, click on the splitter. If you click on either of the SplitContainerPanels, you will select them instead. Also you can use the drop down menu in the property grid to select the SplitContainer...
  • How do I use the WebBrowser as a File Browser?

    The WebBrowser can be used as a file browser by giving it a URL of a folder on the file system. For an example of this see WebBrowserSamples.
  • How do I use the WebBrowser to host a Document?

    The WebBrowser can be used to host an Office document, Flash animation, or PDF file by giving it the URL of the file. For an example of this see WebBrowserSamples.
  • How do I use the WebBrowser as a XSLT Viewer?

    The WebBrowser can be used to view an XML file by giving it the Url of the file. For an example of this see WebBrowserSamples.
  • How do I host my web app controls in WinForms?

    For an example of this, see http://msdn2.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting
  • How do I use the WebBrowser as an Outlook style html viewer?

    You can access, and write to, the HTML behind a web page being displayed by the WebBrowser using the WebBrowser.DocumentText property. For an example of this see WebBrowserSamples.
  • How do I use the WebBrowser as a HTML editor?

    You can access, and write to, the HTML behind a web page being displayed by the WebBrowser using the WebBrowser.DocumentText property. For an example of this see WebBrowserSamples.
  • How do I build a tabbed browser?

    You can build a tabbed browser by combining a TabControl with multiple WebBrowser controls. For a simple example of this see WebBrowserSamples.
  • Why does my application with multiple WebBrowser controls use so much memory?

    The WebBrowser control is a resource-intensive control. Be sure to call the Dispose method when you are finished using the control to ensure that all resources are released in a timely fashion. You must call the Dispose method on the same thread that...
  • Where can I find information on the native interfaces?

    The WebBrowser control is primarily a managed wrapper of the WebBrowser ActiveX object. There are four main unmanaged interfaces that are wrapped in one form or another: IWebBrowser2 – The core WebBrowser interface. DWebBrowserEvents2 – The...
  • Why doesn't the debugger catch exceptions in webBrowser events?

    Note: It is recommended that during development you put try catch blocks around the contents of all WebBrowser methods. Since the core of the managed WebBrowser is an unmanaged ActiveX control, it captures all exceptions thrown in its methods before they...
  • Why can't I set my object for scripting?

    In VS 2005, the form is no longer COM-Visible by default. This prevents it from being set as the object for scripting. To allow scripting to target the form, do the following: In VS select "Project" from the main menu Select "<YourAppName>...
  • Why don't I get <I>&lt;event name here&gt;</I> from the WebBrowser?

    The most likely reason that you are not getting a particular event from the WebBrowser is that that event is hidden. Since the WebBrowser is an ActiveX control it differs in the standard events that it raises.
  • How do I display my own code in the web browser?

    You can access, and write to, the HTML behind a web page being displayed by the WebBrowser using the WebBrowser.DocumentText property. For an example of this see WebBrowserSamples.
  • Why do I get an exception in my progress changed method?

    Sometimes e.MaximumProgress returns a value of 0. If you are trying to control a ProgressBar by dividing e.CurrentProgress by e.MaximumProgress, or by setting a ProgressBar's Maximum to e.MaximumProgress, you will get a divide by zero exception. To...
  • How do I include a picture from my resources in my HTML?

    The simplest approach to accomplish this is to save the html file and the associated images to a temp directory, and navigate the WebBrowser to that html file.
  • How do I get my page to display my language correctly?

    If a web page is not displaying a language correctly, be sure that the web page: Uses correctly formed HTML Contains the Content-type metatag: < META http-equiv="Content-Type" content="text/html; charset =ENC-JP"> Where ENC-JP...
  • How do I set the WebBrowser.Url?

    The webBrowser.Url is not a string, but rather is a Uri object . If you still want to use a string to set the WebBrowser.Url you can do so in one of following ways: webBrowser.Url = new Uri("path string"); webBrowser.Navigate("path string"...