C# Input Box
Date Revised: August 18 2009
Visual Studio 2005 | C#
Sometimes when coding in VB it's sometimes nice to have access to a simple input box. As of C# 3.0,
this feature still does not exist. I miss that feature in C# but not to worry, it's fairly easy to create
your own input box. This is a very simple implementation.
Let's say you have a form where you want your form to collect a person's name by throwing open an input
box. Add a new form to your project called InputBox and add a textBox control, an OK
button, and a Cancel button. Set the following form properties:
ControlBox = false
FormBorderStyle = FixedToolWindow
AcceptButton = your OK button
CancelButton = your Cancel button
Open the code file and wire it up like so...
12 public
partial class
InputBox : Form
13 {
14
// the InputBox
15
private static
InputBox newInputBox;
16
// the string that will be returned to the calling form
17
private static
string returnString;
18
19
public InputBox()
20
{
21
InitializeComponent();
22
}
23
24
public static
string Show(string inputBoxText)
25
{
26
newInputBox = new InputBox();
27
newInputBox.Text = inputBoxText;
28
newInputBox.ShowDialog();
29
return returnString;
30
}
31
32
private void buttonOk_Click(object sender, EventArgs e)
33
{
34
returnString = textBoxString.Text;
35
newInputBox.Dispose();
36
}
37
38
private void buttonCancel_Click(object sender, EventArgs e)
39
{
40
returnString = string.Empty;
41
newInputBox.Dispose();
42
}
43
44
// only used to add a little color to the background
45
private void InputBox_Paint(object sender, PaintEventArgs e)
46
{
47
Graphics g = e.Graphics;
48
Rectangle rec = new
Rectangle(0, 0, this.Width -
1, this.Height - 1);
49
LinearGradientBrush l =
new LinearGradientBrush(rec, Color.LightSteelBlue,
Color.Snow, LinearGradientMode.Vertical);
50
g.FillRectangle(l, rec);
51
}
52
53 }
Now go to the calling forms button click event and just add the following code: In this case, I'm adding
the results from the InputBox to a label on my form.
18 private
void buttonName_Click(object sender,
EventArgs e)
19
{
20
labelName.Text = InputBox.Show("Please
enter your name");
21
}