2012-04-22 126 views
0

我有一个多选择框一些字符串,每次用户选择一个值,它会相应地更改像这样:C# - 多选择列表框更改值

 if (lstSpecial.SelectedIndex == 0) 
     { 
      special1.Price = 18; 

     } 
     else if (lstSpecial.SelectedIndex == 1) 
     { 

      special1.Price = 25; 

     } 
     else if (lstSpecial.SelectedIndex == 2) 
     { 
      special1.Price = 40; 

     } 
     else if (lstSpecial.SelectedIndex == 3) 
     { 
      special1.Price = 30; 

     } 

,并为我工作正常,但是我怎样才能做到这一点,以便如果用户从列表框中选择超过1个值,那么Special1.Price将分别存储每个值?我发现当我尝试选择2个或更多时,这些值会被最后一个选定的值覆盖。

Price属性只是一个简单的get和set。

谢谢

+0

... make一个可以实际处理多个值的数组或列表?另外,您可能需要使用[switch语句](http://goo.gl/f0Yh2)。 – lordcheeto 2012-04-22 19:19:46

+0

将列表框的SelectionMode属性更改为“One”。因为允许用户选择多个项目是没有意义的。 – 2012-04-22 20:00:04

回答

1

要循环访问列表框中的所有选定项目,您应该使用SelectedIndices,它是所选项目的从零开始的索引的集合。

如果...有数组名称价格,写起来容易多了,如果需要更好的扩展(如果lstSpecial包含4个以上的项目,您可能需要检查以避免边界失败。 )。

const int[] prices = new int[]{18,25,40,30}; 
int total = 0; 
foreach(int index in lstSpecial.SelectedIndices) 
    total += prices[index]; 
special1.Price = total; 
0

价格是一个属性,如你所说,可能是int类型。它一次只能保存一个值。如果你想保存多个值,你需要使用一个集合。您可以将价格声明为列表,然后您可以在if语句中添加每个价格。在下面的行上的东西。
声明你的价格属性,如:

public List<int> Price {get;set;} 

然后:(它在下列情况下更好地使用交换机)

if (lstSpecial.SelectedIndex == 0) 
     { 
      special1.Price.Add(18); 

     } 
     else if (lstSpecial.SelectedIndex == 1) 
     { 

      special1.Price.Add(25); 

     } 
     else if (lstSpecial.SelectedIndex == 2) 
     { 
      special1.Price.Add(40); 

     } 
     else if (lstSpecial.SelectedIndex == 3) 
     { 
      special1.Price.Add(30); 

     } 

这样,您将拥有所有的选择价格。您可以通过检查他们:

foreach(int p in special1.Price) 
{ 
Console.WriteLine(p); 
} 

我不知道你的类结构,但如有特殊类代表一个单一的项目,那么它最好有“特殊”的集合,然后添加的价格为他们每个人