Click here to Skip to main content
Email Password   helpLost your password?

Introduction

The great thing about OOP and .NET is that you should never have to find yourself coding the same thing over and over again. Reusability is the name of the game. So when I recently found myself in the vicious cycle of re-coding the same interface component, I thought that surely there was a better way.

Background

I frequently need to create little "wizards" and other applications that work with files and folders. The "industry standard" way of locating these resources is to put a TextBox on the page, and a little icon of a folder next to that, and use the icon folder to launch the browse dialog, storing the results in the TextBox. Surely, you've seen this a thousand times, and if you were building a web application, there is already an object to do this. Not so in Windows Forms, however.

Every time I needed to use this functionality, I had to:

Well, that's a lot of coding to do over and over. And I got tired of it. So I created the BrowseField.

Features of the BrowseField

Using the BrowseField control is as simple as dropping it onto a page, setting the properties up the way you like them in the IDE, and then querying the Text value for the result. Or, you could set the properties programmatically like this:

BrowseField1.Caption = "This is my label text"
BrowseField1.CaptionStyle = BrowseField.CaptionStyles.Top
BrowseField1.FileDialogFilter = "All Files (*.*)|*.*"
BrowseField1.FileDialogFilterIndex = 1
BrowseField1.BrowseType = BrowseField.BrowseTypes.File
BrowseField1.BorderStyle = BorderStyle.FixedSingle

Note that you do not need to setup any code to display the dialog boxes, handle drag and drop operations, or handle resizing operations. For the most part, any changes you make are purely cosmetic. It just works.

BrowseList

Shortly after releasing the BrowseField control, I realized that I often used a ListBox control in much the same way - to gather multiple folder and file names. This is even more of a hassle than using the TextBox, as I usually add several PictureBox controls used to Add, Delete and Edit the paths entered. Checks for duplicate paths are needed as well. And in my opinion, some critical events were left out of the ListBox control - ItemAdded(), ItemRemoved(), and ItemChanged(). These needed to be implemented too.

Features of BrowseList

I think I should also mention that both controls are written in VB.NET. However, as you already know, that won't stop it from working with C# or any other .NET compliant language. There isn't a great deal of commenting in the code - as this is really more of a tool than a tutorial, I didn't see the need for it. Also, since these are composite controls, they are very simple in nature.

Licensing

I always like to list my projects as "ThankYouWare". That is, if you use them, please send me a "Thank You" email letting me know if you like them, and any features or improvements you'd like to see. The controls are open source, you may modify them at will (just don't ask me to fix your modified code). If you redistribute the original or modified code, please credit me somewhere, even if it's just in the code comments.

Breaking Changes

While I hate to make "breaking changes" in controls, I thought it was necessary with this control. The original versions of these controls had a minimal interface, and instead of providing access to the child controls through shadowed properties, I simply exposed the child controls directly. This worked, and certainly exposed every aspect of the child controls to the programmer, but it allowed the programmer to "break" the functionality of the code, and wasn't VS.NET-IDE friendly. (Changes made in the properties grid of the IDE tended to disappear randomly.) Frankly, it was just poor programming.

In version 2, all the important properties and events have been exposed directly. Now the programmer cannot "break" the control's built-in validation and security. It also means that the controls play nice with the IDE. As well, the Caption (Label) is entirely new.

Known Problems

There is a funny little "bug" in the resizing of the controls sometimes. For example, if you open the sample project and change drag the form's width so that it is very small, then re-expand it, the right side of the browse controls goes off the edge of the form. I'm not sure why this is taking place. Also, while very minor, there are icons associated with the controls, but they don't appear to be showing up. If anyone knows of a fix to these problems, I'll be happy to update the code and credit you in the code as well. Thanks.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralWeb Application
malhotrm
17:09 2 May '07  
I am building a web application and would like to get the pathname of a particular folder? How do I do this?

Manav Malhotra
GeneralRe: Web Application
jagadishdandin
21:58 17 May '07  
I am also interested in using this control in a web application. How to do this?

Manav if you find something do please let me also know.

Thanks
Jagadish

I receive every breath i breathe.

GeneralIs it possible to have the buttons as a separate control?
mlyons
9:23 25 Apr '07  
I really like this dll, but was wondering if it was possible to have the buttons as an optional separate control (So that you could hide the buttons and instead use a control to have the buttons in another location, or along the top, etc.). I was also wondering if it was possible to change the images for the buttons. I'm more curious than anything.

Thanks again for a great dll. This is a godsend.
GeneralRe: Is it possible to have the buttons as a separate control?
Todd Davis
9:30 25 Apr '07  
I don't remember anything being built-in to support this, however the source code is included and is license free, so please feel free to modify it for your needs. Maybe I'll revisit this control someday and bring it up to 2.0 since it still seems to be popular.

-Todd Davis (toddhd@gmail.com)

QuestionTextChanged Event not visible
SkipSnyder
18:12 6 Apr '07  
I read the discussion by FauthD dated 12:07 18 Oct '05 about the visibility of the TextChanged event. I have the same problem.

I don't completely follow Fauth's explanation of the workaround. I would like access to the event. Any advice?


D.D. "Skip" Snyder
671 Crescent Ct.
Grand Junction, CO 81505
skips@bresnan.net

GeneralSo... how do I use it?
Perry2
13:00 13 Mar '07  
I downloaded the source, compiled it, copied the dll to my source, and added a reference to it.

So how do I get it to show up on the toolbox so I can use it?

GeneralRe: So... how do I use it?
Todd Davis
16:05 13 Mar '07  
Right click on your toolbox in VS
(If you want to, make a new tab)
Choose to add items
Choose Browse
Browse to the dll
OK your way through
The components will now show up in your toolbox
Drag and drop them on the form


-Todd Davis (toddhd@gmail.com)

GeneralThanks
datlq2003@yahoo.com
23:10 11 Apr '06  
Thanks for sharing!
GeneralCurrentDirectory Changed
Josema
7:04 8 Mar '06  
I've notice that after browse for folder or for file, the current Application directory is changed to the selected folder.

To solve this problem, i've added two lines of code, in the function btnSearch_Click

At the start of the function
string sCurDir = Directory.GetCurrentDirectory ();
And, at the end of the function

Directory.SetCurrentDirectory ( sCurDir );
Regards
GeneralDiscussion: Shall the ListBox1 be public?
FauthD
4:49 20 Oct '05  
Hi,
in my case I need access to the list box and as a QnDirty solution I made it public.
I think it would be better to expose a more general interface for this, but I am not a basic guy (..,C,CPP,MFC and now a bloddy beginner in C#)

Many regards, Dieter Smile
GeneralAdditional event for BrowseList
FauthD
4:45 20 Oct '05  
Hi,
I needed an event that fires after all items have been added. So I created the event ItemsAdded and called RaiseEvent for it after all loops containing the event ItemAdded,
The code is to much to post here (few places), but you get the idea.
@Todd: send me a p-mail, then I can mail you the files..
I also added the "preloading current path/file" extention I did for the BrowseField.

Thanks for this class, Dieter Smile
GeneralBug and fix in BrowseList Delete_Click
FauthD
4:39 20 Oct '05  
Hi,
in single slection mode you will get an exception (out of range). The reason is that the SelectedItem is invalid in the second time of the loop. (the count does not get decremented)
I added an exit in case it is single selection mode.
Warning: I had no time to check the other selection modes.

Private Sub PictureDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureDelete.Click
While ListBox1.SelectedItems.Count > 0
ListBox1.Items.Remove(ListBox1.SelectedItem)
RaiseEvent ItemRemoved(Me, e)
If (ListBox1.SelectionMode = SelectionMode.One) Then
Exit While
End If
End While
End Sub


Good luck, Dieter Smile
QuestionTextChanged is not working here
FauthD
7:07 18 Oct '05  
Hi,
the event does not show up in the event list of the form.
it has something to do with the name of the event.
Renaming to xTextChanged for example does work.

As a workaround I build this event in. it is even better for my app:

Public Event TextValid(ByVal sender As Object, ByVal e As EventArgs)

in Textbox1_TextChanged:
If TextIsValid(Text) Then
RaiseEvent TextValid(Me, New EventArgs)
End If

and the whole sub:
Private Sub Textbox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
If _BrowseType = BrowseTypes.File And _FilenameOnly And Text.IndexOf("\") > -1 Then Text = Text.Substring(Text.LastIndexOf("\") + 1)
RaiseEvent TextChanged(sender, e)

If TextIsValid(Text) Then
RaiseEvent TextValid(Me, New EventArgs)
End If

End Sub




Thanks for this class! Dieter Smile
Generalpreloading current path/file
FauthD
7:01 18 Oct '05  
Hi,
all my programs must be user friendly. One part of that is that paths and filenames must be stored in registry and be shown the next time. For that I use the iProfile class from Alvaro Mendez (http://www.codeproject.com/csharp/ReadWriteXmlIni.asp).
A small change is required to to the BrowseField to expose the stored values to the user:
I just added two lines (one for files, one for folders) before the control actually gets opened:
OpenFileDialog1.FileName = TextBox1.Text
FolderBrowserDialog1.SelectedPath = TextBox1.Text

Not sure if that will show nice in the forum:
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
If _BrowseType = BrowseTypes.File Then
OpenFileDialog1.FileName = TextBox1.Text
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
End If
Else
FolderBrowserDialog1.SelectedPath = TextBox1.Text
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
TextBox1.Text = FolderBrowserDialog1.SelectedPath
End If
End If
End Sub

Thanks for this class! Dieter Smile
GeneralSweet
skitzallykat
16:27 3 Aug '05  
Thanks for the incredibly useful dll's!Cool
GeneralCaption fix, tooltip, and file validation.
Robert Freeman
5:34 7 Mar '05  
Smile Smile Cool Nice control.

The icon only shows up if you add it to your toolbox from the DLL.   It will not show up in the My User Controls section.

Here is the code with the "Caption" fix, tooltip, and file validation.   Add a tooltip (Tooltip1) to the form, then you can copy the code.

Imports System.ComponentModel

Public Class BrowseField
      Inherits System.Windows.Forms.UserControl

#Region " Windows Form Designer generated code "

      Public Sub New()
            MyBase.New()

            'This call is required by the Windows Form Designer.
            InitializeComponent()

            'Add any initialization after the InitializeComponent() call

      End Sub

      'UserControl1 overrides dispose to clean up the component list.
      Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                  If Not (components Is Nothing) Then
                        components.Dispose()
                  End If
            End If
            MyBase.Dispose(disposing)
      End Sub

      'Required by the Windows Form Designer
      Private components As System.ComponentModel.IContainer

      'NOTE: The following procedure is required by the Windows Form Designer
      'It can be modified using the Windows Form Designer.  
      'Do not modify it using the code editor.
      Friend WithEvents PanelTop As System.Windows.Forms.Panel
      Friend WithEvents PanelBottom As System.Windows.Forms.Panel
      Friend WithEvents PanelIndent As System.Windows.Forms.Panel
      Friend WithEvents PanelPicture As System.Windows.Forms.Panel
      Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
      Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
      Friend WithEvents OpenFileDialog1 As System.Windows.Forms.OpenFileDialog
      Friend WithEvents FolderBrowserDialog1 As System.Windows.Forms.FolderBrowserDialog
      Friend WithEvents LabelTop As System.Windows.Forms.Label
      Friend WithEvents LabelLeft As System.Windows.Forms.Label
      Friend WithEvents ToolTip1 As System.Windows.Forms.ToolTip

      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.components = New System.ComponentModel.Container
            Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(BrowseField))
            Me.PanelTop = New System.Windows.Forms.Panel
            Me.LabelTop = New System.Windows.Forms.Label
            Me.PanelBottom = New System.Windows.Forms.Panel
            Me.PanelPicture = New System.Windows.Forms.Panel
            Me.PictureBox1 = New System.Windows.Forms.PictureBox
            Me.TextBox1 = New System.Windows.Forms.TextBox
            Me.PanelIndent = New System.Windows.Forms.Panel
            Me.LabelLeft = New System.Windows.Forms.Label
            Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog
            Me.FolderBrowserDialog1 = New System.Windows.Forms.FolderBrowserDialog
            Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
            Me.PanelTop.SuspendLayout()
            Me.PanelBottom.SuspendLayout()
            Me.PanelPicture.SuspendLayout()
            Me.PanelIndent.SuspendLayout()
            Me.SuspendLayout()
            '
            'PanelTop
            '
            Me.PanelTop.Controls.Add(Me.LabelTop)
            Me.PanelTop.Dock = System.Windows.Forms.DockStyle.Top
            Me.PanelTop.Location = New System.Drawing.Point(0, 0)
            Me.PanelTop.Name = "PanelTop"
            Me.PanelTop.Size = New System.Drawing.Size(288, 20)
            Me.PanelTop.TabIndex = 0
            '
            'LabelTop
            '
            Me.LabelTop.AutoSize = True
            Me.LabelTop.Location = New System.Drawing.Point(0, 2)
            Me.LabelTop.Name = "LabelTop"
            Me.LabelTop.Size = New System.Drawing.Size(0, 16)
            Me.LabelTop.TabIndex = 1
            '
            'PanelBottom
            '
            Me.PanelBottom.Controls.Add(Me.PanelPicture)
            Me.PanelBottom.Controls.Add(Me.TextBox1)
            Me.PanelBottom.Controls.Add(Me.PanelIndent)
            Me.PanelBottom.Dock = System.Windows.Forms.DockStyle.Fill
            Me.PanelBottom.Location = New System.Drawing.Point(0, 20)
            Me.PanelBottom.Name = "PanelBottom"
            Me.PanelBottom.Size = New System.Drawing.Size(288, 20)
            Me.PanelBottom.TabIndex = 1
            '
            'PanelPicture
            '
            Me.PanelPicture.Controls.Add(Me.PictureBox1)
            Me.PanelPicture.Dock = System.Windows.Forms.DockStyle.Right
            Me.PanelPicture.Location = New System.Drawing.Point(264, 0)
            Me.PanelPicture.Name = "PanelPicture"
            Me.PanelPicture.Size = New System.Drawing.Size(24, 20)
            Me.PanelPicture.TabIndex = 1
            '
            'PictureBox1
            '
            Me.PictureBox1.Image = CType(resources.GetObject("PictureBox1.Image"), System.Drawing.Image)
            Me.PictureBox1.Location = New System.Drawing.Point(3, 3)
            Me.PictureBox1.Name = "PictureBox1"
            Me.PictureBox1.Size = New System.Drawing.Size(16, 16)
            Me.PictureBox1.TabIndex = 0
            Me.PictureBox1.TabStop = False
            Me.ToolTip1.SetToolTip(Me.PictureBox1, "Browse")
            '
            'TextBox1
            '
            Me.TextBox1.AllowDrop = True
            Me.TextBox1.Dock = System.Windows.Forms.DockStyle.Fill
            Me.TextBox1.Location = New System.Drawing.Point(0, 0)
            Me.TextBox1.Name = "TextBox1"
            Me.TextBox1.Size = New System.Drawing.Size(288, 20)
            Me.TextBox1.TabIndex = 2
            Me.TextBox1.Text = ""
            '
            'PanelIndent
            '
            Me.PanelIndent.Controls.Add(Me.LabelLeft)
            Me.PanelIndent.Dock = System.Windows.Forms.DockStyle.Left
            Me.PanelIndent.Location = New System.Drawing.Point(0, 0)
            Me.PanelIndent.Name = "PanelIndent"
            Me.PanelIndent.Size = New System.Drawing.Size(0, 20)
            Me.PanelIndent.TabIndex = 0
            '
            'LabelLeft
            '
            Me.LabelLeft.AutoSize = True
            Me.LabelLeft.Location = New System.Drawing.Point(0, 3)
            Me.LabelLeft.Name = "LabelLeft"
            Me.LabelLeft.Size = New System.Drawing.Size(0, 16)
            Me.LabelLeft.TabIndex = 2
            Me.LabelLeft.Visible = False
            '
            'BrowseField
            '
            Me.Controls.Add(Me.PanelBottom)
            Me.Controls.Add(Me.PanelTop)
            Me.Name = "BrowseField"
            Me.Size = New System.Drawing.Size(288, 40)
            Me.PanelTop.ResumeLayout(False)
            Me.PanelBottom.ResumeLayout(False)
            Me.PanelPicture.ResumeLayout(False)
            Me.PanelIndent.ResumeLayout(False)
            Me.ResumeLayout(False)

      End Sub

#End Region

#Region " Variable Declarations"
      Public Enum CaptionStyles
            Top
            Left
            OutDent
      End Enum
      Enum BrowseTypes
            File
            Folder
      End Enum
      Public Enum ValidationModes
            None
            OnLoseFocus
      End Enum

      Private _validationMode As ValidationModes = ValidationModes.None
      Private _captionStyle As CaptionStyles = CaptionStyles.Top
      Private _outdent As Integer = 20
      Private _BrowseType As BrowseTypes = BrowseTypes.Folder
      Private _FilenameOnly As Boolean = False
#End Region

#Region "Events"
      'Declare the DrawingModeChanged Event
      Public Shadows Event TextChanged(ByVal sender As Object, ByVal ev As EventArgs)
      Public Event TextInvalid(ByVal sender As Object, ByVal e As EventArgs)
#End Region

#Region " Custom Properties"
      <Category("Behavior"), DefaultValue(""), Description("Sets the initial directory for the file or folder browser dialog")> _
      Public Property InitialDirectoy() As String
            Get
                  Return OpenFileDialog1.InitialDirectory
            End Get
            Set(ByVal Value As String)
                  OpenFileDialog1.InitialDirectory = Value
                  FolderBrowserDialog1.SelectedPath = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(CaptionStyles.Top), Description("Describes where the caption label is positioned relative to the textbox")> _
      Public Property CaptionStyle() As CaptionStyles
            Get
                  Return _captionStyle
            End Get
            Set(ByVal Value As CaptionStyles)
                  _captionStyle = Value
                  Redraw()
            End Set
      End Property

      <Category("Appearance"), DefaultValue(""), Description("The text value of the caption label")> _
      Public Property Caption() As String
            Get
                  Return LabelTop.Text
            End Get
            Set(ByVal Value As String)
                  LabelTop.Text = Value
                  LabelLeft.Text = Value
                  Redraw()
            End Set
      End Property

      <Category("Appearance"), DefaultValue(20), Description("The amount of space the label is outdented from the textbox, for Wizard 97 applications.")> _
      Public Property OutDent() As Integer
            Get
                  Return _outdent
            End Get
            Set(ByVal Value As Integer)
                  _outdent = Value
                  Redraw()
            End Set
      End Property

      <Category("Behavior"), DefaultValue(ValidationModes.None), Description("When to validate the text and raise the InvalidText event.")> _
      Public Property ValidationMode() As ValidationModes
            Get
                  Return _validationMode
            End Get
            Set(ByVal Value As ValidationModes)
                  _validationMode = Value
            End Set
      End Property


      <Category("Behavior"), DefaultValue(BrowseTypes.File), Description("Specifies the type of search to be done, file or folder.")> _
      Public Property BrowseType() As BrowseTypes
            Get
                  Return _BrowseType
            End Get
            Set(ByVal Value As BrowseTypes)
                  _BrowseType = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(""), Description("If a path to a file is selected, this returns only the file name.")> _
      Public ReadOnly Property FileName() As String
            Get
                  If _BrowseType = BrowseTypes.File And Text.IndexOf("\") > -1 Then
                        Return Text.Substring(Text.LastIndexOf("\") + 1)
                  Else
                        Return ""
                  End If
            End Get
      End Property

      <Category("Behavior"), DefaultValue(False), Description("If set to true and in file mode, the text will reflect only the selected filename.")> _
      Public Property FilenameOnly() As Boolean
            Get
                  Return _FilenameOnly
            End Get
            Set(ByVal Value As Boolean)
                  _FilenameOnly = Value
            End Set
      End Property
#End Region

#Region "Custom Procedures"
      ''' -----------------------------------------------------------------------------
      ''' <summary>
      ''' Validates that the text entered is of the correct BrowseType (file or folder)
      ''' and exists on the drive.
      ''' </summary>
      ''' <param name="FileNameOnlyPath">Path to use if in FileNameOnlyMode.   Include a trailing "\" or "/".</param>
      ''' <returns>True if valid, otherwise false.</returns>
      ''' <remarks>
      ''' </remarks>
      ''' <history>
      '''      [robertf]     3/4/2005     Created
      ''' </history>
      ''' -----------------------------------------------------------------------------
      Public Function TextIsValid(ByVal FileNameOnlyPath As String) As Boolean
            Select Case Me.BrowseType
                  Case BrowseTypes.File
                        FileNameOnlyPath &= Me.Text
                        Return System.IO.File.Exists(FileNameOnlyPath)
                  Case BrowseTypes.Folder
                        Return System.IO.Directory.Exists(Me.Text)
            End Select
      End Function

      ''' -----------------------------------------------------------------------------
      ''' <summary>
      ''' Validates that the text entered is of the correct BrowseType (file or folder)
      ''' and exists on the drive.
      ''' </summary>
      ''' <returns>True if valid, otherwise false.</returns>
      ''' <remarks>
      ''' </remarks>
      ''' <history>
      '''      [robertf]     3/4/2005     Created
      ''' </history>
      ''' -----------------------------------------------------------------------------
      '''  
      Public Function TextIsValid() As Boolean
            Return TextIsValid("")
      End Function

#End Region

#Region " Exposed Child Control Properties"

      <Category("Behavior"), DefaultValue(System.Windows.Forms.CharacterCasing.Normal), Description("Indicates if all characters should be left alone or converted to uppercase or lowercase.")> _
      Public Property CharacterCasing() As System.Windows.Forms.CharacterCasing
            Get
                  Return TextBox1.CharacterCasing
            End Get
            Set(ByVal Value As System.Windows.Forms.CharacterCasing)
                  TextBox1.CharacterCasing = Value
            End Set
      End Property

      <Browsable(False), Category("Appearance"), Description("The length of the currently selected text.")> _
      Public Property SelectionLength() As System.Int32
            Get
                  Return TextBox1.SelectionLength
            End Get
            Set(ByVal Value As System.Int32)
                  TextBox1.SelectionLength = Value
            End Set
      End Property

      <Category("Behavior"), DefaultValue(True), Description("Determines if the text can be edited by hand.")> _
Public Property EditEnabled() As System.Boolean
            Get
                  Return TextBox1.Enabled
            End Get
            Set(ByVal Value As System.Boolean)
                  TextBox1.Enabled = Value
            End Set
      End Property

      <Category("Behavior"), DefaultValue(""), Description("Indicates the character to display for password input for single-line edit controls.")> _
      Public Property PasswordChar() As System.Char
            Get
                  Return TextBox1.PasswordChar
            End Get
            Set(ByVal Value As System.Char)
                  TextBox1.PasswordChar = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(System.Windows.Forms.ScrollBars.None), Description("Indicates, for multi-line edit controls, which scroll bars will be shown for this control.")> _
      Public Property ScrollBars() As System.Windows.Forms.ScrollBars
            Get
                  Return TextBox1.ScrollBars
            End Get
            Set(ByVal Value As System.Windows.Forms.ScrollBars)
                  TextBox1.ScrollBars = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(""), Browsable(True), Description("The text value of the control.")> _
      Public Shadows Property Text() As System.String
            Get
                  Return TextBox1.Text
            End Get
            Set(ByVal Value As System.String)
                  TextBox1.Text = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(System.Windows.Forms.HorizontalAlignment.Left), Description("Indicates how the text should be aligned for edit controls.")> _
      Public Property TextAlign() As System.Windows.Forms.HorizontalAlignment
            Get
                  Return TextBox1.TextAlign
            End Get
            Set(ByVal Value As System.Windows.Forms.HorizontalAlignment)
                  TextBox1.TextAlign = Value
            End Set
      End Property

      <Category("Appearance"), Description("The background color used to display text and graphics in the control.")> _
      Public Property TextBackColor() As System.Drawing.Color
            Get
                  Return TextBox1.BackColor
            End Get
            Set(ByVal Value As System.Drawing.Color)
                  TextBox1.BackColor = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(System.Windows.Forms.BorderStyle.Fixed3D), Description("Indicates whether or not the edit control should have a border.")> _
      Public Property BorderStyle() As System.Windows.Forms.BorderStyle
            Get
                  Return TextBox1.BorderStyle
            End Get
            Set(ByVal Value As System.Windows.Forms.BorderStyle)
                  TextBox1.BorderStyle = Value
            End Set
      End Property

      <Browsable(False), DefaultValue(True), Category("Behavior"), Description("Indicates if the edit control can undo the previous action.")> _
      Public ReadOnly Property CanUndo() As System.Boolean
            Get
                  Return TextBox1.CanUndo
            End Get
      End Property

      <Category("Appearance"), DefaultValue(System.Drawing.KnownColor.WindowText), Description("The foreground color used to display text in the control.")> _
      Public Property TextForeColor() As System.Drawing.Color
            Get
                  Return TextBox1.ForeColor
            End Get
            Set(ByVal Value As System.Drawing.Color)
                  TextBox1.ForeColor = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(System.Drawing.KnownColor.WindowText), Description("The foreground color used to display the caption.")> _
      Public Property CaptionForeColor() As System.Drawing.Color
            Get
                  Return LabelTop.ForeColor
            End Get
            Set(ByVal Value As System.Drawing.Color)
                  LabelTop.ForeColor = Value
                  LabelLeft.ForeColor = Value
            End Set
      End Property

      <Category("Behavior"), Description("Indicates that the selection should be hidden when the edit control loses focus.")> _
      Public Property HideSelection() As System.Boolean
            Get
                  Return TextBox1.HideSelection
            End Get
            Set(ByVal Value As System.Boolean)
                  TextBox1.HideSelection = Value
            End Set
      End Property

      <Category("Behavior"), DefaultValue(32767), Description("Specifies the maximum number of characters that can be entered into the edit control.")> _
      Public Property MaxLength() As System.Int32
            Get
                  Return TextBox1.MaxLength
            End Get
            Set(ByVal Value As System.Int32)
                  TextBox1.MaxLength = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(""), Description("Tooltip caption for the textbox.")> _
      Public Property Tooltip() As String
            Get
                  Return Me.ToolTip1.GetToolTip(Me.TextBox1)
            End Get
            Set(ByVal Value As String)
                  Me.ToolTip1.SetToolTip(Me.TextBox1, Value)
            End Set
      End Property

      <Category("Appearance"), DefaultValue("Browse"), Description("Tooltip caption for the folder icon.")> _
      Public Property BrowseIconTooltip() As String
            Get
                  Return Me.ToolTip1.GetToolTip(Me.PictureBox1)
            End Get
            Set(ByVal Value As String)
                  Me.ToolTip1.SetToolTip(Me.PictureBox1, Value)
            End Set
      End Property

      <Browsable(False), DefaultValue(False), Category("Behavior"), Description("Indicates if the text in the edit control has been modified by the user.")> _
      Public Property Modified() As System.Boolean
            Get
                  Return TextBox1.Modified
            End Get
            Set(ByVal Value As System.Boolean)
                  TextBox1.Modified = Value
            End Set
      End Property

      <Category("Behavior"), Description("Controls whether the text in the edit control can be changed or not.")> _
      Public Property [ReadOnly]() As System.Boolean
            Get
                  Return TextBox1.ReadOnly
            End Get
            Set(ByVal Value As System.Boolean)
                  TextBox1.ReadOnly = Value
            End Set
      End Property

      <Browsable(False), DefaultValue(""), Category("Appearance"), Description("The currently selected text.")> _
      Public Property SelectedText() As System.String
            Get
                  If Not TextBox1.SelectedText Is Nothing Then Return TextBox1.SelectedText
            End Get
            Set(ByVal Value As System.String)
                  If Not Value Is Nothing Then TextBox1.SelectedText = Value
            End Set
      End Property

      <Browsable(False), DefaultValue(0), Category("Appearance"), Description("The beginning of the currently selected text.")> _
      Public Property SelectionStart() As System.Int32
            Get
                  Return TextBox1.SelectionStart
            End Get
            Set(ByVal Value As System.Int32)
                  TextBox1.SelectionStart = Value
            End Set
      End Property

      <Browsable(False), DefaultValue(0), Description("The number of characters contained in the text of the control.")> _
      Public ReadOnly Property TextLength() As System.Int32
            Get
                  Return TextBox1.TextLength
            End Get
      End Property

      <Browsable(False), DefaultValue(True), Category("Focus"), Description("Checks if this control can receive the focus.")> _
      Public Shadows ReadOnly Property CanFocus() As System.Boolean
            Get
                  Return TextBox1.CanFocus
            End Get
      End Property

      <Browsable(False), DefaultValue(True), Category("Focus"), Description("Checks if this control can be selected.")> _
      Public Shadows ReadOnly Property CanSelect() As System.Boolean
            Get
                  Return TextBox1.CanSelect
            End Get
      End Property

      <Browsable(False), DefaultValue(False), Category("Focus"), Description("Determines if this control is currently capturing all mouse input.")> _
      Public Shadows Property Capture() As System.Boolean
            Get
                  Return TextBox1.Capture
            End Get
            Set(ByVal Value As System.Boolean)
                  TextBox1.Capture = Value
            End Set
      End Property

      <Browsable(False), DefaultValue(False), Description("Determines if this control or one if its children currently has the focus.")> _
   Public Shadows ReadOnly Property ContainsFocus() As System.Boolean
            Get
                  Return TextBox1.ContainsFocus
            End Get
      End Property

      <Category("Behavior"), Description("The shortcut menu to display when the user right-clicks the control.")> _
      Public Shadows Property ContextMenu() As System.Windows.Forms.ContextMenu
            Get
                  Return TextBox1.ContextMenu
            End Get
            Set(ByVal Value As System.Windows.Forms.ContextMenu)
                  TextBox1.ContextMenu = Value
            End Set
      End Property

      <Browsable(False), DefaultValue(False), Description("Determines if this control has focus.")> _
      Public Shadows ReadOnly Property Focused() As System.Boolean
            Get
                  Return TextBox1.Focused
            End Get
      End Property

      <Category("Appearance"), Description("The font used to display text in the control.")> _
      Public Property TextFont() As System.Drawing.Font
            Get
                  Return TextBox1.Font
            End Get
            Set(ByVal Value As System.Drawing.Font)
                  TextBox1.Font = Value
            End Set
      End Property

      <Category("Appearance"), Description("The font used to display the caption in the control.")> _
      Public Property CaptionFont() As System.Drawing.Font
            Get
                  Return LabelTop.Font
            End Get
            Set(ByVal Value As System.Drawing.Font)
                  LabelTop.Font = Value
                  LabelLeft.Font = Value
            End Set
      End Property
      <Category("Appearance"), DefaultValue(""), Description("The title to display in the file dialog.")> _
      Public Property FileDialogTitle() As System.String
            Get
                  Return OpenFileDialog1.Title
            End Get
            Set(ByVal Value As String)
                  OpenFileDialog1.Title = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(""), Description("The file filter for the file dialog.")> _
      Public Property FileDialogFilter() As System.String
            Get
                  Return OpenFileDialog1.Filter
            End Get
            Set(ByVal Value As String)
                  OpenFileDialog1.Filter = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(1), Description("The filter index of the filter to use in the file dialog.")> _
      Public Property FileDialogFilterIndex() As System.Int32
            Get
                  Return OpenFileDialog1.FilterIndex
            End Get
            Set(ByVal Value As Integer)
                  OpenFileDialog1.FilterIndex = Value
            End Set
      End Property

      <Category("Appearance"), DefaultValue(""), Description("The description displayed above the tree in the folder dialog box.")> _
      Public Property FolderDialogDescription() As String
            Get
                  Return FolderBrowserDialog1.Description
            End Get
            Set(ByVal Value As String)
                  FolderBrowserDialog1.Description = Value
            End Set
      End Property
#End Region

#Region " Rendering Functions"
      Private Sub Redraw()
            Select Case _captionStyle
                  Case CaptionStyles.Top
                        DrawTopStyle()
                  Case CaptionStyles.Left
                        DrawLeftStyle()
                  Case CaptionStyles.OutDent
                        DrawOutDentStyle()
            End Select
      End Sub
      Private Sub DrawTopStyle()
            LabelLeft.Visible = False
            PanelIndent.Width = 0
            LabelTop.Visible = True
            PanelTop.Height = LabelTop.Height
      End Sub

      Private Sub DrawOutDentStyle()
            LabelLeft.Visible = False
            PanelIndent.Width = _outdent
            LabelTop.Visible = True
            PanelTop.Height = LabelTop.Height
      End Sub

      Private Sub DrawLeftStyle()
            LabelTop.Visible = False
            PanelTop.Height = 0
            LabelLeft.Visible = True
            PanelIndent.Width = LabelLeft.Width
      End Sub
#End Region

#Region " Handled Events "
      Private Sub BrowseField_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Resize
            If _captionStyle = CaptionStyles.Left Then
                  If Me.Width < LabelLeft.Width + PictureBox1.Width Then Me.Width = LabelLeft.Width + PictureBox1.Width
                  If Me.Height <> TextBox1.Height + 4 Then Me.Height = TextBox1.Height + 4
            Else
                  If Me.Width < LabelTop.Width + PictureBox1.Width Then Me.Width = LabelTop.Width + PictureBox1.Width
                  If Me.Height <> LabelTop.Height + TextBox1.Height + 4 Then Me.Height = LabelTop.Height + TextBox1.Height + 4
            End If
      End Sub

      Private Sub Textbox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
            If _BrowseType = BrowseTypes.File And _FilenameOnly And Text.IndexOf("\") > -1 Then Text = Text.Substring(Text.LastIndexOf("\") + 1)
            RaiseEvent TextChanged(sender, e)
      End Sub

      Private Sub TextBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox1.DragEnter
            If e.Data.GetDataPresent(DataFormats.FileDrop) Then
                  e.Effect = DragDropEffects.All
            Else
                  e.Effect = DragDropEffects.None
            End If
      End Sub

      Private Sub TextBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles TextBox1.DragDrop
            Dim files As String() = CType(e.Data.GetData("FileDrop", False), String())
            Dim s As String
            For Each s In files
                  Text = s
            Next
      End Sub

      Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
            If _BrowseType = BrowseTypes.File Then
                  If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
                        TextBox1.Text = OpenFileDialog1.FileName
                  End If
            Else
                  If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
                        TextBox1.Text = FolderBrowserDialog1.SelectedPath
                  End If
            End If
      End Sub

      Private Sub BrowseField_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Leave
            If Me.ValidationMode = ValidationModes.OnLoseFocus AndAlso Not Me.TextIsValid Then
                  RaiseEvent TextInvalid(Me, New EventArgs)
            End If
      End Sub

#End Region

End Class

Robert R Freeman
GeneralRe: Caption fix, tooltip, and file validation.
Robert Freeman
7:55 7 Mar '05  
One correction: the enum OnLoseFocus should be OnLeave.
GeneralThe control's icons ...
W. Kleinschmit
3:31 2 Feb '05  
Lookup "ToolboxBitmapAttribute[^]" in the MSDN Library Documentation.
Change your class declarations as follows:

From Public Class BrowseField
to <ToolboxBitmap(GetType(BrowseField), "BrowseField.bmp")> Public Class BrowseField
and From
Public Class BrowseList
to <ToolboxBitmap(GetType(BrowseList), "BrowseList.bmp")> Public Class BrowseList
The icons will still not appear in the "My User Controls" Tab of the Toolbox, but when you add them manually to any other project (via the "Add/Remove Items ..." context menu item) you will see them.

Hope this helps.
GeneralRe: The control's icons ...
Todd Davis
3:35 2 Feb '05  
Thanks for this suggestion, and the one on resizing. I will try them both, and if they work, I will upload those changes (and credit you in the code of course). Thanks so much!

I hope the controls were helpful to you.

-Todd Davis (toddhd@gmail.com)
GeneralThe resizing bug ...
W. Kleinschmit
2:48 2 Feb '05  
Perhaps you should just not set the width of the controls 'by hand' when AnchorStyles.Right is set?

Suggestion: Insert the following lines at the beginning of BrowseField_Resize resp. BrowseList_Resize.

If (Me.Anchor And (AnchorStyles.Right Or AnchorStyles.Left)) = (AnchorStyles.Right Or AnchorStyles.Left) Then
Exit Sub
End If

Hope this helps.
Cool Cool piece of work anyway. (Got my 5) Cool
GeneralFew questions
sdcougar
10:03 13 Jan '05  
First of all I love the control it has helped me alot.

I am having some problems with changing the properties of ListBox, I had to change the selection mode in the initialization code because it was not applying the value set in the properties list.

Also I am trying to change the ListBox to an OwnerDrawFixed mode, so I can colorize the strings, but that event is not firing.

Great job just a few quirks left.
GeneralRe: Few questions
Todd Davis
10:11 13 Jan '05  
Thanks, glad it is helping you out, at least somewhat.

I had the same problem with the properties, if I tried to set them through the designer. Even if they "took" once, they would dissapear after making some other change in VS.NET. I think this is a problem with VS, but either way, it's a pain.

I started work a newer version of these controls that had more features, but the biggest feature is that all the properties are being properly overridden, so you won't have to do this:
BrowseField1.TextBox.BorderStyle = BorderStyle.FixedSingle;

Instead, it will look more like this:
BrowseField1.BorderStyle = BorderStyle.FixedSingle;

I don't know when this be available. I started working on it a few months back, and then my "day job" got real busy, so I haven't put much time into it. When it is done however, it will be updated right here in CodeProject.

-Todd Davis (toddhd@gmail.com)
GeneralRe: Few questions
sdcougar
10:50 13 Jan '05  
Any idea how i can get the ownerdraw working for the list box?

I thought it would be a simple line like this but apparently not:

this.CompareToList.ListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(ListBoxDrawItem);

Thanks again.
GeneralRe: Few questions
sdcougar
16:15 13 Jan '05  
Acually nevermind my response, I dont know why I didnt try this before, I just programatically set the draw mode and it works fine.

Fantastic work. Keep it up.
GeneralDragDrop registration failed
zoomba
10:55 5 Nov '04  
First of all control is great. I do get exception: DragDrop registration failed. What I do is:
- Create a new windows form MyForm
- Drop BrowseField from my toolbox on the form
- Write this code to use the form:
MyForm mf= new MyForm();
DialogResult dr = mf.ShowDialog();

At ShowDialog I get exception: DragDrop registration failed

What should I do to use it2

By the way I work on WinXp SP2 and .NET 1.1 Sp1.

Thanks.





DK


Last Updated 31 Jan 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010