How to tips and tricks for Microsoft Visual Studio .net

Monday, August 23, 2010

InputBox for c#

One of the little things that has been left out of the c# tool box is the vb style input box that allows you to input a string into a text box and have the string returned back to you.

This is my solution...

Create a little FixedToolWindow that looks like this...

It needs a label, a text box and two buttons.

Name your form and controls:

Form - InputBox.
Caption Label - lblCaption.
Text Box - txtInputText.
Ok Button - btnOk.
Cancel Button - btnCancel.

lblCaption is used to display any instructions you have for the user, txtInputText for the text to input, btnOk to cause dialogResult.OK to be returned to the calling code and btnCancel to cause DialogResult.Cancel to be returned to the calling code.

Set the form's AcceptButton and CancelButton properties to btnOk and btnCancel respectively.

You must go to the designer code for the form itself and set the caption label and input text box to public so they will be accessible when you use the form.

     public System.Windows.Forms.Label lblCaption;  
     public System.Windows.Forms.TextBox txtInputText;  

Set the DialogResult of btnOk button to "OK", and the DialogResult of btnCancel button to "Cancel"

Then use the following code on the form to receive a caption and title to display and default value for the input string...

   public partial class InputBox : Form  
   {  
     /// <summary>  
     /// Caption for the Input Box  
     /// </summary>  
     private string Caption;  
     /// <summary>  
     /// Title for the Input Box  
     /// </summary>  
     private string Title;  
     /// <summary>  
     /// Default text for the Imput Box  
     /// </summary>  
     private string DefaultText;  
     /// <summary>  
     /// Provides a string based input function to get feedback from the user  
     /// </summary>  
     /// <param name="_Caption"></param>  
     /// <param name="_Title"></param>  
     /// <param name="_DefaultText"></param>  
     public InputBox(string _Caption, string _Title, string _DefaultText)  
     {  
       InitializeComponent();  
       Caption = _Caption;  
       Title = _Title;  
       DefaultText = _DefaultText;  
     }  
     private void InputBox_Load(object sender, EventArgs e)  
     {  
       this.Text = Title;  
       lblCaption.Text = Caption;  
       txtInputText.Text = DefaultText;  
     }  
   }  

You will use it like this...

         InputBox inputbox = new InputBox(Caption, Title, DefaultText);  
         DialogResult dlg = inputbox.ShowDialog();  
         if (dlg == DialogResult.OK)  
         {  
           string firstName = inputbox.txtInputText.Text;
         }  

As you can see it is then pretty simple to use, and has pretty much the same functionality as the vb Input Box control.

1 comment:

  1. Please leave feedback. I would love to know if my blog actually helps you.

    ReplyDelete