我正在尝试使用c#中的switch语句在文本框中显示一些文本,并根据我从组合框中选择的选项在另一个文本框中显示数字。我创建了自己的名为“Devices”的类,并在类中创建了几个对象。我还为每个对象提供了几个属性(例如DeviceName,DeviceRating)。但是,当我启动表单并从我的组合框中选择一个选项时,第一个选项按计划工作(文本显示在相关文本框中),但所有选项都显示空白文本框。有关为什么会发生这种情况的任何想法?
以下是我的属性代码:
private void Form1_Load(object sender, EventArgs e)
{
// Gives properties of each object in the 'Devices' class.
WashingMachine.DeviceName = "Washing Machine";
WashingMachine.DeviceRating = 1200;
Dishwasher.DeviceName = "Dishwasher";
Dishwasher.DeviceRating = 1;
;
OvenHob.DeviceName = "Oven/Hob";
OvenHob.DeviceRating = 1;
;
TowelRail.DeviceName = "Towel Rail";
TowelRail.DeviceRating = 1;
Hairdryer.DeviceName = "Hairdryer";
Hairdryer.DeviceRating = 1;
Shower.DeviceName = "Shower";
Shower.DeviceRating = 1;
}
以下是我创建的类的代码:
class Devices
{
public string DeviceName;
public int DeviceRating;
public int UsedMins;
}
以下是我在类中创建新对象的代码:
// Creating new objects under the 'Devices' class.
Devices WashingMachine = new Devices();
Devices Dishwasher = new Devices();
Devices OvenHob = new Devices();
Devices TowelRail = new Devices();
Devices Hairdryer = new Devices();
Devices Shower = new Devices();
Devices PhoneCharger = new Devices();
Devices TabletCharger = new Devices();
Devices ElectricBlanket = new Devices();
这里是switch语句控制组合框中每个案例的情况(注意组合框列表与列出的对象的顺序相同):
// Puts a Name and Power Rating into the textboxes based on the chosen device
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBox1.SelectedIndex)
{
case 0:
DeviceName.Text = WashingMachine.DeviceName;
PowerRating.Text = WashingMachine.DeviceRating.ToString();
break;
case 1:
DeviceName.Text = Dishwasher.DeviceName;
PowerRating.Text = Dishwasher.DeviceName.ToString();
break;
case 2:
DeviceName.Text = OvenHob.DeviceName;
PowerRating.Text = OvenHob.DeviceRating.ToString();
break;
case 3:
DeviceName.Text = TowelRail.DeviceName;
PowerRating.Text = TowelRail.DeviceRating.ToString();
break;
case 4:
DeviceName.Text = Hairdryer.DeviceName;
PowerRating.Text = Hairdryer.DeviceRating.ToString();
break;
case 5:
DeviceName.Text = Shower.DeviceName;
PowerRating.Text = Shower.DeviceRating.ToString();
break;
}
}
答案 0 :(得分:1)
这有点不匹配。您是否为ComboBox命名为comboBox1
并使用名为comboBox3_SelectedIndexChanged()
的事件?
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBox1.SelectedIndex)
{
不应该是
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBox3.SelectedIndex)
{
请原谅,如果偶然保留了偶数名称。另外,你的代码中是否真的有这些额外的分号?
Dishwasher.DeviceRating = 1;
;
和
OvenHob.DeviceRating = 1;
;