Using the Visual Basic Input Box in C#
In all versions of Visual Basic as far back as I can remember, there has been the venerable InputBox function which has been great for quickly getting an input from the user. VB.NET has it too, but C# doesn't, and it is sorely missed.However, there is a simple solution. We can simply "borrow" the InputBox from VB.NET, by adding a reference to the required assemblies. To do this in Visual Studio, follow the steps below
- In the Solution Explorer, right click on the "References" folder and select "Add Reference..."
- In the ".NET" tab, scroll down and select the "Microsoft.VisualBasic" entry, then click "Ok".
String Prompt = "Please enter your name";
String Title = "Input Required";
String Default = "Bob";
Int32 XPos = ((SystemInformation.WorkingArea.Width/2)-200);
Int32 YPos = ((SystemInformation.WorkingArea.Height/2)-100);
String Result =
Microsoft.VisualBasic.Interaction.InputBox(Prompt,Title,Default,XPos,YPos)
if(Result != "") {
MessageBox.Show("Hello " + Result);
} else {
MessageBox.Show("Hello whoever you are...");
}
Here we are just asking for a user's name (with a default of "Bob") using a (roughly) centred InputBox, and then just saying hello with a standard message box. Unfortunately, along with inheriting the InputBox itself, .NET has also inherited its String return type - you wont find a nice object encapsulating the response like we get with the DialogResult.
Because of this we need to check the string returned - if the user cancels the dialog, the string will be zero-length, otherwise it will be whatever the user typed into the input box.
Note here that I've used the full name for the InputBox function. There is nothing to stop you sticking using Microsoft.VisualBasic; at the top of your class to avoid having to type out the full thing each time.
Nothing special is required for compilation or distribution if you use this. I hope you find this useful - it has saved me a fair bit of time and effort when all you need is some simple text input and dont need a dedicated form.
Back
22.07.2006.
Thank you so much!
Pie-Pacifique
01.02.2007
Its a very good article, that helped me a lot
Anand
27.04.2007
Thanks a lot. It was very useful.
Ponnusamy G
07.06.2007
Thanks for the info, I have been looking for this for months :)