Click here to Skip to main content
15,899,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create a 'code', which is dependent on a combobox selection and I have implemented a random number generator also. So if the user selects Aluminium in the combobox I want a code to be created of 'AL093847', for example. At the moment the code is only being generated for 'Copper' im not sure why. can anyone help

private void button1_Click(object sender, EventArgs e)
{

    Random generator = new Random();
    int r = generator.Next(1000000);
    string rnd = r.ToString("D6");

    string Material = "";

        if (comboBox1.SelectedText == "Iron")
        {
            Number.Text = Number.Text + "FE" + rnd;
        }

        else if (comboBox1.SelectedText == "Aluminium")
        {
            Number.Text = Number.Text + "AL" + rnd;
        }
         else
        {
            Number.Text = Number.Text + "CU" + rnd;
        }


    }


What I have tried:

private void button1_Click(object sender, EventArgs e)
{

    Random generator = new Random();
    int r = generator.Next(1000000);
    string rnd = r.ToString("D6");

    string Material = "";

        if (comboBox1.SelectedText == "Iron")
        {
            Number.Text = Number.Text + "FE" + rnd;
        }

        else if (comboBox1.SelectedText == "Aluminium")
        {
            Number.Text = Number.Text + "AL" + rnd;
        }
         else
        {
            Number.Text = Number.Text + "CU" + rnd;
        }


    }
Posted
Updated 15-Apr-18 17:35pm

Based on what presented, I'm guessing, the comboBox1.SelectedText is always returning empty string, that why it go to the else statement. Change the code to use the .Text property

WinForms ComboBox: text vs. selectedtext - Stack Overflow[^]
 
Share this answer
 
Try to replace:
C#
if (comboBox1.SelectedText == "Iron")

with:
C#
if (comboBox1.Text == "Iron")
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900