简体   繁体   中英

How to add textbox text with listbox items

Suppose a list box contains '%' and 'rs' and we need to enter number in text box.How to calculate % if '%' is selected from list box and how to add number from text box with list box if 'rs is selected.'

This is what I have tried so far:

double a = double.Parse(textBox4.Text);
double b = double.Parse(textBox9.Text);
double c = a - ((a * b) / 100);
if (e.KeyData == Keys.Enter)
{
    if (listBox1.SelectedIndex == listBox1.FindString("%"))
    {
        textBox8.Text = c.ToString();
    }

    listBox2.Focus();
}

Simply create an eventhandler for the "KeyDown" event in textBox2.

private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        CalculateResult();
    }
}

And then use this to calculate your result.

private void CalculateResult()
{
    try
    {
        double a = double.Parse(textBox1.Text);
        double b = double.Parse(textBox2.Text);
        double c = 0;//Set the result to 0 as a default.
        if (listBox1.SelectedItem == "%")
        {
            c = a / b * 100;
        }
        if (listBox1.SelectedItem == "rs")
        {
            c = a + b;
        }
        textBox3.Text = c.ToString();
    }
    catch(Exception err)
    {
        MessageBox.Show(err.Message);//Display error message if necessary.
    }
}

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