我想在c#中使用switch语句在一个文本框中显示一些文本,并在另一个文本框中根据我从组合框中选择的选项显示一个数字显示。我已经创建了自己的类“Devices”,并在课堂中创建了多个对象。我还给每个对象一些属性(例如DeviceName,DeviceRating)。但是,当我开始表单并从我的组合框中选择一个选项时,第一个选项按计划运行(文本显示在相关文本框中),但所有选项都显示空白文本框。任何想法为什么这可能会发生?使用组合框与switch语句c#
这里是我的属性代码:
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语句控制组合框中每个case的情况(注意com bobox列表与列出的对象的顺序相同):
// 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;
}
}
看起来像它应该工作好了,根据我们可以看到。当您尝试将它们分配给文本框时,放置一些断点并查看“Hairdryer.DeviceName”等的值。 –
你可以添加项目到组合框,使用显示成员来显示设备名称和设置文本框为'((设备)comboBox1.SelectedItem)。设备名称等 –
为什么名为'comboBox3_SelectedIndexChanged'和'switch'使用'comboBox1.SelectedIndex'。 'comboBox1&comboBox3? –