Here are some frequently asked questions about Windows Forms and their answers.
Browse by Tags
All Tags » Using Controls (RSS)
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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;...
|
-
|
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.
|
-
|
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...
|
-
|
The System Renderer renders ToolStrips similar to Win32 look and feel. You can use with or without VisualStyles by ToolStripManager.VisualStylesEnabled = false;
|
-
|
Set RoundedEdges = false. You may also have to override OnRendererToolStripBorder and not call base. ((ToolStripProfessionalRenderer)ToolStripManager.Renderer).RoundedEdges = false;
|
-
|
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;...
|
-
|
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...
|
-
|
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...
|
-
|
Generally its this - background, item background, item foregound effects, toolstrip border. OnRenderToolStripBackground OnRender[Label|Button|MenuItem...]Background OnRenderItemText OnRenderItemArrow OnRenderItemImage OnRenderToolStripBorder The toolstrip...
|
-
|
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...
|
-
|
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...
|
-
|
For one ToolStrip ProfessionalColorTable colorTable = new ProfessionalColorTable(); colorTable.UseSystemColors = true; toolStrip.Renderer = new ToolStripProfessionalRenderer(colorTable); For the entire app: ToolStripManager.VisualStylesEnabled = false;
|
-
|
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...
|
-
|
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...
|
-
|
See http://blogs.msdn.com/jfoscoding/articles/472113.aspx
|
-
|
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...
|
-
|
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.
|
-
|
The MenuStrip is visible=true and even though it is empty, we render it. Simply set Visible=false to fix this.
|
-
|
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...
|
-
|
ToolStripManager is a static class that handles application wide ToolStrip related tasks such as merging, settings and renderer exposure.
|
-
|
This is a rather spiffy article: http://blogs.msdn.com/jfoscoding/archive/2005/03/03/384430.aspx
|
-
|
Handle WM_NCHITTEST. See http://blogs.msdn.com/jfoscoding/archive/2005/04/20/410231.aspx for more detail.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
class Form3 : Form { private ContextMenuStrip fruitContextMenuStrip; public Form3() { // new ContextMenuStrip fruitContextMenuStrip = new ContextMenuStrip(); // sync opening event fruitContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler...
|
-
|
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...
|
-
|
Yes. ToolStrip supports the ImageAnimator class - if you assign an Animated GIF to the Image property it will automatically render the animation.
|
-
|
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...
|
-
|
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....
|
-
|
StatusStrip replaces the StatusBar control. Special features of the StatusBar is a custom Table Layout, support for the form's sizing grip and Spring.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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.
|
-
|
toolStripButton.CheckOnClick = true; toolStripButton.CheckedChanged += new EventHandler(toolStripButton_CheckedChanged);
|
-
|
Yes, ToolStripLabel has an IsLink property that will render it in a link style. LinkColor, LinkVisited and LinkBehavior are exposed.
|
-
|
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.
|
-
|
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...
|
-
|
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.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
Use ToolStripItem.ImageScaling = ToolStrimItemImageScaling.None
|
-
|
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...
|
-
|
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...
|
-
|
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;
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
By default the ToolStrip is double buffered; taking advantage of the OptimizedDoubleBuffer API offered in Windows Forms 2.0.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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
|
-
|
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.
|
-
|
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...
|
-
|
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.
|
-
|
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...
|
-
|
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...
|
-
|
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.
|
-
|
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...
|
-
|
Wrapping radio button/checkbox http://blogs.msdn.com/jfoscoding/articles/478300.aspx Wrapping text http://blogs.msdn.com/jfoscoding/articles/478299.aspx
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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) ...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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
|
-
|
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
|
-
|
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...
|
-
|
When you change the Culture property on the MaskedTextBox, the Mask picker dialog will show the pre-defined masks for that culture.
|
-
|
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.
|
-
|
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.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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.
|
-
|
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.
|
-
|
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.
|
-
|
For an example of this, see http://msdn2.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting
|
-
|
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.
|
-
|
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.
|
-
|
You can build a tabbed browser by combining a TabControl with multiple WebBrowser controls. For a simple example of this see WebBrowserSamples.
|
-
|
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...
|
-
|
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...
|
-
|
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...
|
-
|
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>...
|
-
|
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.
|
-
|
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.
|
-
|
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...
|
-
|
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.
|
-
|
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...
|
-
|
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"...
|
-
|
A possible reason that the WebBrowser's Url value changes when navigating to a site is due to a redirect that would cause the Url to change from its original value.
|
-
|
Set auto complete source of the TextBox or ComboBox being used for the address to "All Url's" or to "custom". See WebBrowserSamples for an example.
|
-
|
Currently there is no workaround to avoid the click noise when clicking on a link.
|
-
|
The WebBrowser control does not work in partial trust. This class makes security demands at the class level, therefore a SecurityException is thrown when a derived class or any caller in the call stack does not have full trust permission. For details...
|
-
|
To get the Url that the WebBrowser is navigating to in a new window, use DWebBrowserEvents2::NewWindow3. This method is not exposed by IntelliSense. For information on how to use it, see: http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=7228 for...
|
-
|
To navigate to an addresses that contains escaped characters (such as %20) be sure to use the webBrowser.Navigate(String) method instead of the webBrowser.Navigate(Uri) method. The Uri method escapes these characters by default, while the String method...
|
-
|
To block pop-ups, use the following registry key: HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER) SOFTWARE Microsoft Internet Explorer Main FeatureControl FEATURE_WEBOC_POPUPMANAGEMENT For more information on this topic, see http://msdn.microsoft.com/library...
|
-
|
Be sure that AllowNavigation is set to true. This property not only prevents users from making the WebBrowser navigate, but also prevents the WebBrowser from programmatically being given a new Url.
|
-
|
For an example of this, see http://msdn2.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting
|
-
|
To control XP SP2 security features, you can set various registry keys. For detailed information, see: http://www.microsoft.com/technet/prodtechnol/winxppro/maintain/sp2brows.mspx
|
-
|
For information on how to disable JavaScript, and adjusting WebBrowser permissions in general see the white paper on "Adjusting WebBrowser Permissions With InternetSecurityManager" up on MSDN.
|
-
|
You can use the IsNull operator. // the outer quotes are double-quotes // the inner quotes are two single-quotes // Fax is the column mapping name dataView1.RowFilter = "IsNull(Fax, '') = ''"; // for a numeric null in custNumber...
|
-
|
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...
|
-
|
Take a look at Tim Anderson's The HtmlEditor - a C# control that wraps MSHTML for a sample control that wraps MSHTML. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Look at the following articles to clear the Cache. How to clear the cache when your application hosts a WebBrowser control in Visual Basic .NET (Article ID: 311289) HOW TO: Clear the Cache When Your Application Hosts a WebBrowser Control in Visual C#...
|
-
|
There is a known bug: BUG: The BeforeNavigate2 Event of the WebBrowser Control Does Not Fire If Hosted in a Visual Basic .NET Application (Article ID: 311298) BUG: The BeforeNavigate2 Event of WebBrowser Control Does Not Fire If Hosted in a Visual C#...
|
-
|
You can set the content editable by getting a reference to a IHTMLElement3 element and initializing the contentEditable property with "true". private void EnableEditing() { IHTMLDocument3 doc = (IHTMLDocument3) browser.GetDocument(); if (doc...
|
-
|
We have two suggestions with sample projects how you host a WebBrowser control inside a form and display HTML contents and listen to events such as NavigateComplete or BeforeNavigate. Of course there are many other ways to do this. Download htmlviewer...
|
-
|
When a button is clicked on a ToolBar, the click is sent to the ToolBar not the button. In the ToolBar.ButtonClick event handler, you need add code to check the Button property of the ToolBarButtonClickEventArgs passed to the event handler to determine...
|
-
|
When you drag an item within the TreeView, you can handle the DragOver event for a drag-drop. If you want to drag-drop into a spot that's not currently visible, you can scroll the TreeView by handling the DragOver event: [C#] private void treeView1_DragOver...
|
-
|
Set the TreeView.CheckBoxes property to true. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Handle the TreeView's MouseDown event, and if it is the right-click, then explicitly set focus to the node under the click. private void treeView1_MouseDown( object sender, MouseEventArgs e ) { if ( e.Button == MouseButtons.Right ) treeView1.SelectedNode...
|
-
|
When I get the SelectedNode in the TreeView's Click event, it is the previous selection. How do I get the newly selected node? Use the AfterSelect event instead of the Click event. The Click event is inherited from Control.Click and occurs before...
|
-
|
Try using a MouseMove event handler and checking to see if you have moved to a new node, and if so, set a new tiptext. [C#] private int oldNodeIndex = -1; private ToolTip toolTip1; private void Form1_Load( object sender, EventArgs e ) { toolTip1 = new...
|
-
|
[C#] public int NodeLevel( TreeNode node ) { int level = 0; while ( (node = node.Parent) != null ) ++level; return level; } [Visual Basic] Public Sub NodateLevel(ByVal node as TreeNode) As Integer Dim level as Integer = 0 While Not node Is Nothing node...
|
-
|
The following code snippet demonstrates how you can clone or copy all the nodes in TreeView1 to TreeView2 by clicking on Button1. private void IterateTreeNodes( TreeNode originalNode, TreeNode rootNode ) { foreach ( TreeNode childNode in originalNode...
|
-
|
// Select the first node treeView1.SelectedNode = treeView1.Nodes[0]; Contributed from George Shepherd's Windows Forms FAQ
|
-
|
You can display a context menu when a user right-clicks on a node by handling the TreeView's MouseUp event as shown below: [C#] private void treeView1_MouseUp( object sender, MouseEventArgs e ) { if ( e.Button == MouseButtons.Right ) { Point clickPoint...
|
-
|
A click event will be fired but a node will not be selected when the user clicks to the right of a node. This code snippets show how you can ensure that a node is selected in this scenario: private void treeView1_Click( object sender, EventArgs e ) {...
|
-
|
Here are some VB.Net code snippets to handle the DragEnter, ItemDrag and DragDrop events that provide a solution to this problem. You can get C# code in this sample, TreeViewDnD . Here is some sample handlers. private void treeView2_DragDrop( object sender...
|
-
|
The Treeview control does not support multiple selections but here is sample which demonstrates how this feature can be implemented. Another sample is available at C# .NET TreeView with multiple selection at arsdesign.com . Contributed from George Shepherd's...
|
-
|
The following articles on MSDN give you step by step instructions on how you can populate a TreeView Control with data from an XML document. How To Populate a TreeView Control with XML Data in Visual Basic .NET (Article ID: 308063) HOW TO: Populate a...
|
-
|
When I set a TextBox to Readonly or set Enabled to false, the text color is gray. How can I force it to be the color specified in the ForeColor property of the TextBox? You can download a VB.NET sample. Override the OnPaint event of the TextBox. For example...
|
-
|
Say you have a Parent table related to a Child table related to a GrandChildTable, and you want to bind a TextBox to a column in the GrandChild table. To do this you have to have nested relations defined, and you use this nesting to create the DataMember...
|
-
|
You can handle the textbox's KeyPress event and if you want the keypress to be an overwrite, just select the current character so the keypress will replace it. The attached sample has a derived textbox that has an OverWrite property and a right-click...
|
-
|
Each type has a ToString method that can be used to perform formatting. Also, you can use the String.Format method to format things as well. To format dates, use the ToString member of DateTime. You may want to use the InvariantInfo setting to get culture...
|
-
|
You can set the ContextMenu property of the TextBox to a dummy, empty ContextMenu instance. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Add a handler for your TextBox's KeyDown event. (This assumes you set the AcceptsReturn property to False). Then in your KeyDown eventhandler, have code such as: [C#] if (e.KeyCode = Keys.Enter) SendKeys.Send("{TAB}"); [Visual Basic] If...
|
-
|
There are several of ways to do this. Here are a few: 1) Insert a carriage return, linefeed combination, "\r\n", between lines of text. textBox1.Text = "This is line 1.\r\nThis is line 2"; 2) Use the Environment.NewLine property. This...
|
-
|
You can handle the textbox's KeyPress event and if the char passed in is not acceptable, mark the events argument as showing the character has been handled. Below is a derived TextBox that only accepts digits (and control characters such as backspace...
|
-
|
You can do this by deriving the TextBox, overriding the WndProc method and ignoring these mouse down messages. [C#] public class CustomTextBox : TextBox { protected override void WndProc( ref Message m ) { // WM_NCLBUTTONDOWN WM_LBUTTONDOWN if ( !( ReadOnly...
|
-
|
Set the TextBox.PasswordChar property. textBox1.PasswordChar = '\u25CF'; Contributed from George Shepherd's Windows Forms FAQ
|
-
|
I have a delete key shortcut for my main menu. When my textbox is being edited, pressing delete activates this menu items instead of being processed by the TextBox. How can I get my TextBox to handle this delete? Subclass the TextBox and override its...
|
-
|
Use the CharacterCasing property of the TextBox. textBox1.CharacterCasing = CharacterCasing.Upper; textBox2.CharacterCasing = CharacterCasing.Lower; Contributed from George Shepherd's Windows Forms FAQ
|
-
|
There is a protected SendMessage call you can use for this purpose, so you have to derive from TextBox. public class CustomTextBox : TextBox { private const int EM_XXXX = 0x1234; public int LineIndex { get { return base.SendMessage( EM_XXXX, 0, 0 ); ...
|
-
|
You use the Frameworks OpenFileDialog to implement this functionailty. using System.Text; using System.IO; private void button1_Click( object sender, EventArgs e ) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Open text file" ; dlg...
|
-
|
How do I prevent the user from being able to paste from the clipboard into a TextBox, e.g., through Ctrl+V and the context menu? First set the ContextMenu property of the TextBox to a dummy, empty ContextMenu instance. This will prevent the default context...
|
-
|
You can prevent the beep when the enter key is pressed in a TextBox by deriving the TextBox and overriding OnKeyPress. [C#] public class CustomTextBox : TextBox { protected override void OnKeyPress( KeyPressEventArgs e ) { if ( e.KeyChar == (char) 13...
|
-
|
The following code snippet shows how you can drag a TabPage from TabControl1 and drop it into TabControl2 (whose AllowDrop property must be set to True): [C#] // Source TabControl private void tabControl1_MouseMove( object sender, MouseEventArgs e ) ...
|
-
|
You can use the TabPage's Validating event to prevent a new tab page selection. Here are the steps: 1) Every time the user selects a new tab, make sure that the corresponding tab page gets the focus. You can do so as follows: private void tabControl1_SelectedIndexChanged...
|
-
|
It's a common mistake to try to use the Visible property of the TabPage to make the tab invisible. But this does not work (The Visible property of the TabPage is essentially obsolete). The TabControl doesn't provide you an easy way to do so. The...
|
-
|
To delete a tabpage, you use the tabControl1.Controls.Remove method. To add a new page as the last tab, use the tabControl1.Controls.Add method. Here is some sample code. // remove the selected tab tabControl1.Controls.Remove( tabControl1.SelectedTab...
|
-
|
Set the TabControl.Alignment property to TabAlignment.Bottom. tabControl1.Alignment = TabAlignment.Bottom; You can also change the tabs into buttons using the Appearance property and TabAppearance enums. Contributed from George Shepherd's Windows...
|
-
|
Listen to the Form's Activate event and set focus on the text box (using the Focus method). The common mistake is to try to set Focus in the Form_Load event. This is not possible because no Controls are visible at this time and hence focus cannot...
|
-
|
This seems to be a known issue with the TabControl designer. The designer seems to automatically reorder the tabs while serializing changes made in the designer. To work around this issue, in your constructor, after the call to InitializeComponent, you...
|
-
|
There are a couple of ways you could do select a tab page programmatically. This selects the second Tab page: tabControl.SelectedTab = this.tabPage2 This also selects the second Tab page: tabControl.SelectedIndex= 1; Contributed from George Shepherd's...
|
-
|
Set the TabControl's DrawMode to OwnerDraw, and then handle the DrawItem event to draw things yourself. Here are both VB and C# sample projects that display a gradient tab for the active tabpage. Contributed from George Shepherd's Windows Forms...
|
-
|
You cannot place controls into a StatusBar control in the Designer. However, you can add any number of controls to the StatusBar programmatically through its Controls property. After adding the controls, set their Visible, Location, Bounds and other properties...
|
-
|
The Rich Text Format (RTF) Specification, version 1.6 is available in the MSDN Library. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
There is no direct support for printing rich text in the .NET Framework. To print it, you can use interop with the SendMessage API and these three messages to do your printing. EM_SETTARGETDEVICE : specify the target device EM_FORMATRANGE : format part...
|
-
|
If you visit the selection a character at the time, you can get the current FontStyle and modify it directly to add or remove a style like Bold or Italic. Doing it a character at a time will avoid losing the other styles that are set. The problem with...
|
-
|
To add a hyperlink to the RichTextBox, so that it opens up the link you click on, ensure that DetectUrls property is set to true and call: [C#] private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e) { System.Diagnostics.Process.Start...
|
-
|
You use the LoadFile method of the RichTextBox, passing it a StreamReader based on the resource. So include your RTF file as an embedded resource in your project, say RTFText.rtf. Then load your RichTextBox with code such as Stream stream = GetType()...
|
-
|
There are a couple different methods that can be used here. The first changes focus, so may not be possible if you have controls that fire validation. The second uses interop, which requires full trust. Method 1: The RichTextBox control contains a Lines...
|
-
|
One way to do this is to use the RichTextBox.SaveFile method. private void button1_Click( object sender, EventArgs e ) { // get a file name from the user SaveFileDialog saveFile1 = new SaveFileDialog(); saveFile1.DefaultExt = "*.rtf"; saveFile1...
|
-
|
Use the Rtf property of the control. richTextBox1.Rtf = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl {\f0\fswiss\fcharset0 Arial;}}\viewkind4\uc1\pard\b\i\f0\fs20 This is bold italics.\par }"; Contributed from George Shepherd's Windows...
|
-
|
You must set the AllowDrop property on the RichTextBox control to true, and also handle both the DragEnter and DragDrop events. Add event handlers to the control: [C#] using System.Windows.Forms; richTextBox1.DragEnter += new DragEventHandler( richTextBox1_DragEnter...
|
-
|
You use the SelectionFont and SelectionColor properties. Make sure the control had focus. Then the following code will set the currently selected text to a red-bold-courier font. If no text is currently selected, then any new text typed (or inserted)...
|
-
|
Refer to one of these Knowledge Base articles on MSDN: How To Create a Smooth ProgressBar in Visual Basic .NET (Article ID: 323088) HOW TO: Create a Smooth Progress Bar in Visual C# .NET (Article ID: 323116) Contributed from George Shepherd's Windows...
|
-
|
One solution is to use a panel that has a picturebox placed on it with DockStyle.Fill. This will make the picturebox assume the size of the panel. In addition, set the DockPadding.All property to the width of the desired border. Then in the Panel's...
|
-
|
See the article Scrollable Picture Box by Mike Golds article on C# Corner for a detailed discussion. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
The following code snippet demonstrates how you can drag and copy an image from one picturebox (Source) another (Target): [C#] private void Form1_Load( object sender, EventArgs e ) { // Set AllowDrop of the Target PictureBox to true // as this property...
|
-
|
Since .NET uses it's own format that is not compatible with the EnhancedMetafile format you will have to use reflection to achieve this. (From a posting in the microsoft.public.dotnet.framework.drawing newsgroup) [C#] [DllImport("user32.dll"...
|
-
|
This code snippet shows how you can set your PictureBox's image to be the image from the clipboard: [C#] pictureBox1.Image = (Bitmap) Clipboard.GetDataObject().GetData( DataFormats.Bitmap ); [Visual Basic] pictureBox1.Image = _ CType(Clipboard.GetDataObject...
|
-
|
Make sure to set these flags for your panel, e.g., in its constructor. You will have to derive a class from Panel otherwise if you were initially using the Panel directly. base.SetStyle( ControlStyles.DoubleBuffer | ControlStyles.DoubleBuffer | ControlStyles...
|
-
|
This is because of a bug in the .NET Framework. When tooltips are set on a control that hosts other controls within it (like the NumericUpDown), tooltips are not shown on those child controls. To workaround this issue, do the following in code: [C#] foreach...
|
-
|
You can listen to the Popup event, determine where the mouse was clicked and selectively make the menu items visible in the menu as follows: private void contextMenu1_Popup( object sender, EventArgs e ) { // Get current mouse click position in the control...
|
-
|
The ContextMenu.SourceControl property will specify the latest Control on which the context menu was shown. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
The frame will manage a context menu for you if you set the control's ContextMenu property. Here is some code adding a context menu to a Label. //Add Menus in your form's constructor... this.pictureContextMenu = new ContextMenu(); this.pictureContextMenu...
|
-
|
Override WndProc in your Control and do the following. You should then listen to keyup and show the context menu yourself. [C#] private int const WM_CONTEXTMENU = 0x7b; private int const WM_KEYUP = 0x101; protected override void WndProc(ref Message m...
|
-
|
First keep track of which control is showing the ContextMenu by listening to the menu's Popup event and querying for the SourceControl. Then when you are ready to cancel the popup, do as follows: [DllImport("user32.dll", CharSet=CharSet...
|
-
|
Normally, the context menu will be shown at the center of the control when the keyboard is used to invoke the context menu of a control (Shift+F10, for example). You can customize the location as follows. Override WndProc in the grid and check if the...
|
-
|
To prevent the default context menu of a TextBox from showing up, assign a empty context menu as shown below: textBox1.ContextMenu = new ContextMenu(); Contributed from George Shepherd's Windows Forms FAQ
|
-
|
To automatically close the context menu after a set time interval, you can use a Timer and send an Esc keystroke after the desired time interval as shown: [C#] private void timer1_Tick(object sender, System.EventArgs e) { SendKeys.Send("{ESC}"...
|
-
|
The focused control's ProcessCmdKey will be called first. 1) The Control class implementation of this method will check if there is a ContextMenu associated with the Control and if so let the context menu handle the shortcut. 2) If not handled, the...
|
-
|
Check out G. G. Arun Ganesh's article Working with Menus in C# on C# Corner . Contributed from George Shepherd's Windows Forms FAQ
|
-
|
There are MenuComplete and MenuStart events in the Form that will inform you of the corresponding menu events in the Form. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
This used to be a very useful feature in MFC. You can do something similar with the System.Windows.Forms.Application.Idle event which will get fired when the app becomes Idle. Where you could parse through all the menu items and update their states. Contributed...
|
-
|
Create a "Window" menu in your MDI parent form's menu and then drop another MenuItem into it, setting its MdiList property to true. It will then expand to show all the available MDI children during runtime. Contributed from George Shepherd's...
|
-
|
When you assign Ctrl1, Ctrl2, etc. as shortcuts for MenuItems they show up as Ctrl+D1, Ctrl+D2. This can be worked around by creating and adding the menuitem through code as demonstrated below: [C#] //Create the menuitem MenuItem mymenuItem = new MenuItem...
|
-
|
contextmenu.MenuItems.Add("-"); Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Usually the underline appears only after you press the Alt Key, but you can enable it by changing the Operating System Settings. On Windows XP, Right Click Desktop to bring up the Display Properties Dialog and then choose Appearance tab and then the Effects...
|
-
|
You need to implement an owner drawn menu to add icons to it. Take a look at the Ownerdraw menuitems sample on .netPlus . Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Try code such as: ListViewItem item = new ListViewItem("NewItem"); item.SubItems.AddRange( new string[] { "SubItem1", "SubItem2" ) }; listView1.Items.Add( item ); listView1.Items.Add( new ListViewItem( new string[] { "item1"...
|
-
|
Make sure the ListView has focus when you set the Selected property. For example, if this code is in the click handler for a button, this button will have the focus, and the selection in the list will fail. Set the focus back to the list before you set...
|
-
|
Call the ListView.SelectedItems.Clear method. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
To select the i-th item, you can use code such as // Make sure the listview has focus listView1.Focus(); listView1.Items[ i ].Selected = true; Contributed from George Shepherd's Windows Forms FAQ
|
-
|
I am trying to programmatically change the ForeColor and BackColor properties of subitems in a ListView. Why doesn't this work? Make sure the item's UseItemStyleForSubItems property is set to false. ListViewItem item1 = new ListViewItem( "item1"...
|
-
|
You create a class the implements the IComparer inteface. This interface has a single method that accepts two objects, and returns positive integers if the first object is larger than the second, negative integers if the first object is less than the...
|
-
|
See one of these Microsoft step-by-step articles: HOW TO: Sort a ListView Control by a Column in Visual Basic .NET (Article ID: 319399) HOW TO: Sort a ListView Control by a Column in Visual C# .NET (Article ID: 319401) Contributed from George Shepherd's...
|
-
|
The attached solution contains both C# and VB.NET projects. The solution use Interop with the LVM_GETSUBITEMRECT window's message to loop through each subitem's bounds rectangle until it finds the one that contains the specified mouse click point...
|
-
|
See Creating an Owner-Drawn Listbox on GotDotNet . It derives from Form and implements the owner drawing by handling the DrawItem event and MeasureItem event. You can also download a sample that implements an owner drawn listbox by deriving from ListBox...
|
-
|
The code below minimally handles D&D for a single selection list box by handling four events. The D&D is initiated in MouseDown if the user mouses down on the current selection. The DragEnter event is used to set the dragging effect to copy if...
|
-
|
You can iterate through the list to find the longest text extent using MeasureString, adding a fudge factor if the is present. using ( System.Drawing.Graphics g = listBox1.CreateGraphics() ) { float maxWidth = 0f; float height = 0f; for ( int i = 0; i...
|
-
|
Place a ListBox on your form, set its AllowDrop property and handle both DragEnter and DragDrop as below. private void listBox1_DragEnter( object sender, DragEventArgs e ) { if ( e.Data.GetDataPresent( DataFormats.FileDrop ) ) e.Effect = DragDropEffects...
|
-
|
You have to access the Items of the ListBox using the Items property and clear (or otherwise operate on the items) these. listBox1.Items.Clear(); Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Check out Devinder Arora's article Using ListBox Control in C# on C# Corner . Contributed from George Shepherd's Windows Forms FAQ
|
-
|
The attached EditableList UserControl implements an editable ListBox with an in-place TextBox and Button allowing users to directly edit the contents of the list box. When the user clicks on a selected item, a textbox and a button is shown over the selected...
|
-
|
I'm trying to make the background of my LinkLabel transparent so a PictureBox will show through it. However, if I set the LinkLabel's BackColor property to Transparent the label still has a white background. Why? Controls with a Transparent color...
|
-
|
It looks like the ImageList editor loses the transparency when it does some internal copy or clone of the images. However, it seems that it does work when you add the images in code to the ImageList. One workaround (not so tidy) is to add the images to...
|
-
|
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...
|
-
|
Use the FindStringExact method. For example, to set the ComboBox's ValueMember property to "OrderID", then you could call comboBox1.SelectedIndex = comboBox1.FindStringExact( stringOrderID ); where stringOrderID is the orderID of the row...
|
-
|
Michael Gold discusses this problem in his article How to create a "ComboBox button" in a toolbar in .NET on C# Corner . Contributed from George Shepherd's Windows Forms FAQ
|
-
|
You can subclass ComboBox. In your derived class, make sure you set DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; DropDownStyle = ComboBoxStyle.DropDownList; You also need to handle the DrawItem event to actually implement the drawing. Check...
|
-
|
You can prevent the ComboBox dropping by overriding its WndProc method and ignoring the WM_LBUTTONDOWN and WM_LBUTTONDBLCLK. [C#] using System.Windows.Forms; public class CustomComboBox : ComboBox { protected override void WndProc( ref Message m ) { if...
|
-
|
You can iterate through the list to find the longest text extent using MeasureString, and then use this as the ComboBox width adding a fudge factor for the drop-down button. using ( Graphics g = comboBox1.CreateGraphics() ) { float maxWidth = 0f; foreach...
|
-
|
You can control the height by changing the value of the MaxDropDownItems property of the the ComboBox, which is the maximum number of entries that will be displayed in the drop-down list. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Set the ComboBox's DropDownStyle property to DropDownList. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
Here are some snippets. (Courtesy of) [C#] DataTable list = new DataTable(); list.Columns.Add(new DataColumn("Display", typeof(string))); list.Columns.Add(new DataColumn("Id", typeof(int))); list.Rows.Add(list.NewRow()); list.Rows...
|
-
|
The enum values can be bound to a combobox as follows: MyValues is the enum type [C#] // Setup the binding as follows: comboBox1.DataSource = Enum.GetValues(typeof MyValues); // SelectedValueChanged event for the ComboBox. private void ComboBox1ValueChanged...
|
-
|
Try comboBox1.Items.AddRange( FontFamily.Families ); Contributed from George Shepherd's Windows Forms FAQ
|
-
|
In Usenet posts, MS has acknowledged this bug. The problem is essentially that any time the visibility changes on a CheckedListBox, it loses its previous selections. Naturally this happens all the time in tab controls when changing tabs. This derived...
|
-
|
To check all items, you can use code such as: [C#] for ( int i=0; i < checkedListBox1.Items.Count; ++i ) checkedListBox1.SetItemChecked( i, true ); [Visual Basic] Dim i as Integer For i = 0 To checkedListBox1.Items.Count - 1 checkedListBox1.SetItemChecked...
|
-
|
public class RepeatButton : Button { private Timer timer1; public int Interval { get { return Timer.Interval; } set { Timer.Interval = value; } } private Timer Timer { get { if ( timer1 == null ) { // create and setup the timer timer1 = new Timer(); timer1...
|
-
|
Use the Button's public method PerformClick. Contributed from George Shepherd's Windows Forms FAQ
|
-
|
You can use the Button.Image property to add an image to a button face. Use the Button.ImageAlign (and possibly Button.TextAlign) to layout your button face. You can also implement custom drawing on a button face as described in How do I add custom drawing...
|
-
|
Get a Graphics object for the button and use its MeasureString method to compute the width you need. using ( Graphics g = button1.CreateGraphics() ) float w = g.MeasureString( button1.Text, button1.Font ).Width; button1.Width = (int) w + 12; // 12 is...
|
-
|
Subclass Button and add a custom Paint event handler that does you custom drawing. public class CustomButton : Button { public CustomButton() { Paint += new PaintEventHandler( ButtonPaint ); } private void ButtonPaint( object sender, PaintEventArgs e...
|
-
|
1) Cannot override methods like WndProc, ProcessCmdKey, etc in a derived Control. The class ref for a particular property will let you know about the permission requirements. 2) Cannot call Control.Parent. 3) Cannot call Control.Focus() method. Contributed...
|
-
|
The issues listed here are pertaining to code running in IE in the default Internet Zone. 1) You cannot view Controls inside IE using the 1.0 framework (when running with the permissions in the default Internet Zone). This is however possible with the...
|
-
|
You cannot use a WinForms Control directly in IE, you will have to instead derive from it and then use the derived instance from a custom assembly. These articles introduce the topic: Host Secure, Lightweight Client-Side Controls in Microsoft Internet...
|
-
|
You do this in order to ensure that your component gets disposed along with the contained Form (logical parent). All Form derived classes come with an IContainer field into which many of the .NET components like ImageList and Timer add themselves. The...
|
-
|
You can do this using the bitwise operators. In C# the bitwise operators are & , | and ^ ; in VB they are And (or &), Or and Xor (or ^). Here is code that will toggle whether label1 is anchored on the left. [C#] using System.Windows.Forms; private...
|
-
|
private void Form1_Load( object sender, EventArgs e ) { Bitmap newBmp = new Bitmap(100, 100); Graphics g = Graphics.FromImage(newBmp); g.FillRectangle(new SolidBrush(Color.Red), 0, 0, 33, 100); g.FillRectangle(new SolidBrush(Color.White), 34, 0, 33, 100...
|
-
|
Where do I find an ImageMap-style control? There isn't an ImageMap-style control in the .NET Framework Class Library. However, the article C# Windows Forms ImageMap Control by Ryan LaNeve, September 2002, on The Code Project provides a control with...
|
-
|
See the article Tutorial: Creating C# Class Library (DLL) Using Visual Studio .NET by Mahash Chand on C# Corner . Contributed from George Shepherd's Windows Forms FAQ
|
-
|
button1.Cursor = new Cursor( @"C:\winnt\cursors\hnodrop.cur" ); Contributed from George Shepherd's Windows Forms FAQ
|
-
|
The controls that I've try to add to my form at runtime don't show up. What's wrong? Make sure you implemented and executed code similar to the InitializeComponent method that VS adds to your Windows Forms project for controls added during...
|
-
|
You use System.Reflection to dynamically load a control. This sample loads the SpecControls.ColorControl from SpecControls.dll. [C#] using System.Reflection; Assembly assembly = Assembly.LoadFrom( "SpecControls.dll" ); Type t = assembly.GetType...
|
-
|
There are three steps to adding a control at runtime. Create the control. Set control properties. Add the control to the Form's Controls collection. In general, if you need help on exactly what code you need to add, just look at the code generated...
|
-
|
In VB6, I used control arrays to have a common handler handle events from several controls. How can I do this in Windows Forms? You can specify events from different controls be handled by a single method. When you define your handler, you can list several...
|
-
|
See the Control.Handle property which returns the HWND. Be careful if you pass this handle to some Win32 API as Windows Forms controls do their own handle management so they may recreate the handle which would leave this HWND dangling. Shawn Burke, Microsoft
|
-
|
I am using a Windows Forms control in an Internet Explorer (IE) page. When IE downloads the control, it is distinguishing between upper- and lower-case letters in the web site URL. When I use the same site with different casing - such as http://111.1...
|
-
|
I use a WebBrowser control in a Windows Forms control. When this control is used in an EXE, it works fine. But when I embed this control in a IE web page, the WebBrowser in it doesn't work (could not show any web page). Why can't the WebBrowser...
|
-
|
I have tried to use the '&' (ampersand) character to declare the Alt shortcut in ToolStripMenuItem.Text but it doesn't work. Is there another kind of declaration? In fact it works when I add the ToolStripMenuItem to a MenuStrip.Items but...
|
-
|
Is it possible to have the same items in two different MenuStrip controls, for example the main menu and a context menu? With the entire ToolStrip family of controls we do not have an integrated commanding architecture nor do we support cloning of items...
|
-
|
If the ContextMenuStrip has to replace the ContextMenu control, I'm missing something behind the scenes, because I can't find the Popup event. Is there any other event I can use in its behalf? I think you're looking for the Opening and Opened...
|
-
|
When I make a menu bar, I get a blue background theme. How can I make it the normal Windows menu bar, i.e., grey? You can change any strip control's ToolStrip.RenderMode to System to get system look and feel.
|
-
|
Set the ToolStrip.GripStyle property to Hidden.
|
-
|
There is an XHTML RichTextBox sample on the WindowsForms.net website. See the RichTextBox that Displays XHTML item in the Controls section on the WindowsForms.net Samples page .
|
-
|
Does the ListView in Whidbey support a display like a threaded conversation, much like Outlook Express does in its news reader? I understand the Listview in Win32 can but has this been exposed in managed code yet? The ListView has a NumIndents property...
|
-
|
The DateTimePicker is very limited in its styling since it is what comes built into the operating system. This means that Windows Forms inherited all its limitations that the shell team created (or didn't create -- like flat style features). There...
|
-
|
I have an object that I'm trying to bind its properties to two DateTimePicker controls. class Order { public DateTime OrderPlacedDate { get; } public Nullable<DateTime> ShippedDate { get; } } What is the proper way to bind Nullable DateTime...
|
-
|
I followed the instructions in the article How to: Host Controls in Windows Forms DataGridView Cells in the Visual Studio 2005 Library. I've used this to implement a MaskedTextBox control in a DataGridView. It seems to work but how do I make the "mask"...
|
-
|
I was wondering if it's possible to have a DataGridView list relational data in the same grid by branching the data as can be done in previous controls. It seems any relational data has to be viewed in a separate grid. Am I missing something? You...
|
-
|
I am using a DataGridViewComboBoxColumn in a DataGridView. When the DataSource of the DataGridViewComboBoxColumn has zero items from a SQL Select statement, all the whole will be a mash. How should I deal with this? This has been fixed in future versions...
|
-
|
In fact base.Clone() returns an object of type equals to this.GetType(). A reflection invocation on the default constructor might be done in the DataGridViewTextBox.Clone() method. It seems that the one methodology for implementing ICloneable would be...
|
-
|
I followed the article How to: Host Controls in Windows Forms DataGridView Cells and have inherited from DataGridViewTextBoxCell to create a custom cell for a DataGridView column. When the DataGridView needs to create a new cell in the column the method...
|
-
|
I have a ContextMenuStrip on a DataGridView with some action to perform on the selected record in the grid. My problem is that when the user right-clicks on a record, that record is not selected and he performs the action on an other record. The simple...
|
-
|
You can set a row's HeaderCell.Value property to a value and it will be painted. Alternatively - and fairly easy - handle the RowPostPaint and paint the row number in the header cell like so: Private Sub dataGridView1_RowPostPaint(ByVal sender As...
|
-
|
How do I add a control to a column header like a Button or TextBox? We don't have any built in support for this since column header cells do not have code to allow it to be editable. For a button you can simply custom paint the button by handling...
|
-
|
I wrote this to set the HeaderText in a DataGridView: dataGridView1.AutoGenerateColumns = true; dataGridView1.DataSource = ds; dataGridView1.DataMember = ds.Tables[0].TableName; // change the HeaderText of columns. dataGridView1.Columns[0].HeaderText...
|
-
|
The SoundPlayer will only support WAV files.
|