1

我使用了表单用户控件(而不是 C# winform 中的表单)。

在这个用户控件中,我有一个组合框和一个文本框。

更改组合框时,对于选定的值(1 或 2 或 3),文本框的文本分别以 1 或 2 或 3 开头。

用户可以在文本框中添加 6 位数字,但不能删除或更改 1 或 2 或 3。

我该怎么办?

4

4 回答 4

1

看看这是否可行,它正在处理 TextChanged 事件以验证第一个 Character 是来自 ComboBox 选择的值。

public partial class UserControl1 : UserControl
{
    string mask;

    public UserControl1()
    {
        InitializeComponent();
        textBox1.MaxLength = 7;
        textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
        textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);

    }

    void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsNumber(e.KeyChar) && !( e.KeyChar == 0x8) && !(e.KeyChar == 0xd))
            e.Handled = true;

    }

    void textBox1_TextChanged(object sender, EventArgs e)
    {
        TextBox tb = (TextBox)sender;

        char[] temp = tb.Text.ToCharArray(); //Code to catch any cut and Paste non numeric characters
        foreach (var item in temp)
        {
            if (!(char.IsNumber(item)))
            {
                tb.Text = "";
                break;
            }
        }

        if (tb.TextLength == 0)
        {
            tb.Text = mask[0].ToString();
            tb.SelectionStart = tb.Text.Length;

        }
        else
        {
            if (tb.Text[0] != mask[0])
            {
                tb.Text = mask[0] + tb.Text;
                tb.SelectionStart = tb.Text.Length;
            }
        }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        mask = ((ComboBox)sender).SelectedValue.ToString();
        textBox1.Text = mask;
    }

}
于 2012-11-17T07:02:52.753 回答
0

在组合框 selectedchanged 事件中,将文本框值设置为 1/2/3。设置文本框按键或 keydown 事件以处理用户无法删除/编辑文本框中第一个字符的情况。如果用户尝试删除/编辑第一个字符,则设置您的条件并设置 e.Handled = true。确保向用户发出某种警告,即他无法编辑第一个字母。

cmbBox_SelectionChanged(object sender, SomeEventArgs args)
{
    txtBox.Text = "1";
}

txtBox_KeyPress(object sender, KeyPressEventArgs e)
{
     //Writing a little bit of pseudo code here 'cause I don't have VS on this system.
     if(KeyPressed is delete or if the txtBox.Text string is left with a single character)
         e.Handled = true;
}

您可以类似地处理其他一些情况,例如用户选择整个文本并删除。请检查我是否也错过了组合框中的任何可能案例。也许,您只想在用户选择新值时替换文本框中现有字符串的第一个字符。类似的东西。

于 2012-11-17T06:49:23.527 回答
0

如果你真的想要文本框中的数字,你可能必须处理 KeyPress 事件,并确保用户没有删除你想要开始的数字,或者在你的起始数字前面添加数字。处理 KeyPress 事件还将允许您过滤长度并限制用户只输入数字。

处理此问题的另一种方法是将 Label 控件放在 TextBox 的左侧。将数字放入标签中并允许用户编辑文本框中的文本。操作 UserControl 的 Value 以将两者连接在一起。如果 ComboBox 选择了“2”,则 Label 中的文本将为“2”,用户键入“543”,然后将 User 控件的 Value 属性设置为“2543”。

于 2012-11-17T06:53:06.013 回答
0

不要为事件中的所有情况而烦恼。只需将标签放在文本框之前并使用组合框值设置它。清洁且易于维护。

于 2012-11-17T07:19:57.663 回答