您的位置:首页 > 编程语言 > C#

C#中一个类似inputBox的输入框(转)

2006-05-30 14:21 393 查看
小玩意,很实用(自己太懒)


InputBox class

The InputBox class is a public class with a private constructor. You use it by calling
the static Show method. This method instantiates a new instance of the class, sets
it's properties and returns the result. The result is not a string but a InputBoxResult
object. This object has two properties: OK and Text. OK is a boolean indicating
that the user clicked the OK button and not the Cancel button. The Text contains
the string the user entered.

public static InputBoxResult
Show(string
prompt, string
title,
string defaultResponse,

InputBoxValidatingHandler validator,
int xpos,
int ypos)
{

using
(InputBox form =
new InputBox())
{

form.labelPrompt.Text
= prompt;

form.Text =
title;

form.textBoxText.Text
= defaultResponse;

if
(xpos >= 0
&& ypos
>= 0)
{

form.StartPosition =
FormStartPosition.Manual;

form.Left =
xpos;

form.Top =
ypos;

}

form.Validator =
validator;

DialogResult
result = form.ShowDialog();

InputBoxResult
retval = new
InputBoxResult();

if
(result
== DialogResult.OK) {

retval.Text =
form.textBoxText.Text;

retval.OK =
true;

}

return
retval;

}

}

public static InputBoxResult
Show(string
prompt, string
title,
string defaultText,

InputBoxValidatingHandler validator)
{

return Show(prompt,
title, defaultText, validator,
-1,
-1);

}


Usage

You activate the InputBox by calling the static Show() method. It has 4 required
and 2 optional arguments (using overloading).

private void
buttonTest_Click(object
sender, System.EventArgs e)
{

InputBoxResult result = InputBox.Show("Test prompt:",
"Some title", "Default text",
null);

if (result.OK)
{

textBox1.Text =
result.Text;

}

}


Validation

You can add validation logic using the validator argument. The validator is a InputBoxValidatingHandler
delegate which you can use to validate the Text. The following sample checks whether
the Text is not empty. If so it sets Cancel to true and the Message to 'Required'.

private void
buttonTest_Click(object
sender, System.EventArgs e)
{

InputBoxResult result = InputBox.Show("Test prompt:",
"Some title", "Default text",

new InputBoxValidatingHandler(inputBox_Validating));

if (result.OK)
{

textBox1.Text =
result.Text;

}

}

private void
inputBox_Validating(object
sender, InputBoxValidatingArgs
e) {

if (e.Text.Trim().Length
== 0)
{

e.Cancel
= true;

e.Message
= "Required";

}

}

下载地址:http://www.reflectionit.nl/download.aspx?URL=InputBoxSample.zip
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: