FireFox

我的地盘—我做主

 

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

小玩意,很实用(自己太懒)

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

posted on 2006-05-30 14:21  FireFox  阅读(2183)  评论(0)    收藏  举报

导航