简体   繁体   中英

Selecting a specific item in listbox

I have 6 items in my listbox.

I want to it so that if I click the first 2 in the listbox I can set a random number. I don't need to know how make a random number.

I thought it would be something like this:

if (listBox1.SelectedIndex = 1)
{
    int no1 = random.Next(10, 50);
}

Just after 'if' I see the following error:

Cannot implicitly convert type 'int' to 'bool'

Should be: if (listBox1.SelectedIndex == 1)

The = operator is assignment, == is equality.

You need to use two equal signs to check for equality.

if (listBox1.SelectedIndex == 1)
{
  int no1 = random.Next(10, 50);
}

You can read more about C# equality on MSDN .

Yes in case of int you can't use = operator to check equality you just need to check using == operator, ok in the case of bool compiler can't give any error but it can resign.mean to say.

if (listBox1.SelectedIndex == 1)
 {
   int no1 = random.Next(10, 50);
 }

it's correct one in case of Bool

suppose you have to write.

bool test=false;
if(test=true)
{
 //some code goes here 
 }

it won't give you compiler error it will reassign test.

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