简体   繁体   中英

Formatted text on SelectedIndexChanged in Combobox

In ComboBox.Items , there are three options, 0.25, 0.50, 0.75 . Now user writes a value in ComboBox , eg 1 , and now selects one of those items, the desired comboBox.Text = 1.25 (selecting first option).

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;
        }
    }

This code sets the Text = 0.25 . I want output like entered value + selected item eg 1.25 when user enters 1 and selects 0.25 . And when I debug the above code, the SelectedIndexChanged event run twice, the break point shows comboBox.Text = 1.25 but not on form.

Please try it out and tell me, whether you are looking for the same.

    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); 

    } 

Simply,

    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}");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM