Combobox中SelectedIndexChanged的格式化文本

时间:2015-04-07 04:07:41

标签: c# .net winforms combobox

ComboBox.Items中,有三个选项0.25, 0.50, 0.75。现在,用户在ComboBox中写入一个值,例如1,现在选择其中一个项目,即所需的comboBox.Text = 1.25(选择第一个选项)。

public string cmbBxText = string.Empty;

private void LengthCmbBx_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.lengthCmbBx.Text = 
            (Convert.ToDouble(cmbBxText) 
            + Convert.ToDouble(this.lengthCmbBx.SelectedItem)).ToString();
    }

    private void lengthCmbBx_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode != Keys.Up
            && e.KeyCode != Keys.Right
            && e.KeyCode != Keys.Left
            && e.KeyCode != Keys.Down)
        {
            cmbBxText = this.lengthCmbBx.Text;
        }
    }

此代码设置Text = 0.25。我想要输出entered value + selected item,例如用户输入1.25并选择10.25。当我调试上面的代码时,SelectedIndexChanged事件运行两次,断点显示comboBox.Text = 1.25但不在表单上。

2 个答案:

答案 0 :(得分:0)

请试试看,告诉我,你是否也在寻找同样的东西。

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    { 

            index = comboBox1.Items.IndexOf(comboBox1.Text);

            string temp = comboBox1.Text;
            StringBuilder newSB = new StringBuilder(temp);
            newSB = newSB.Remove(0, 1);
            string newStr =  cmbBxText.ToString() + newSB.ToString();
            cmbBxText.Clear();
            comboBox1.Items.RemoveAt(index);
            comboBox1.Items.Insert(index, newStr); 

    } 

答案 1 :(得分:0)

简单地说,

    private void CmbBx_TextChanged(object sender, EventArgs e)
    {
        if (this.cmbBx.Text != string.Empty 
            && !this.cmbBx.Text.Contains(".25")
            && !this.cmbBx.Text.Contains(".50")
            && !this.cmbBx.Text.Contains(".75"))
        {
            this.cmbBx.Items.Clear();

            this.cmbBx.Items.Add(this.cmbBx.Text + ".25");
            this.cmbBx.Items.Add(this.cmbBx.Text + ".50");
            this.cmbBx.Items.Add(this.cmbBx.Text + ".75");
        }

        if (this.cmbBx.Text == string.Empty)
        {
            this.cmbBx.Items.Clear();
        }

        SendKeys.Send("{F4}");
    }