如何为每个组合框元素指定一个整数值 - c#
我在制作一个计算能源使用量的程序。我有一个家用电器的组合框。当选择电器时,我希望将一个额定功率分配给一个变量,然后计算总能源使用量。我该如何解决它?我应该双击组合框并在方法中编写适当的代码吗?如何为每个组合框元素指定一个整数值 - c#
这是一个Windows窗体应用程序。我所做的全部都是使用设计视图从工具箱中制作的组合框。然后通过单击属性>项目填充组合框。该comboxbox包含一个下拉菜单包含小时(00,01,02,03等),另一个包含分钟(00,15,30,45)。我想从组合框中获取值并对它们进行计算。
于是,我就做什么你问
在这里,我有我的方式加载事件我只是设置的时间数据源和分钟组合框
private void Form1_Load(object sender, EventArgs e)
{
var hours = new int[] {1,2,3,4,5,6,7,8,9,10,11,12};
var mins = new int[] { 0, 15, 45};
hoursComboBox.DataSource = hours;
minsComboBox.DataSource = mins;
}
创建powerCalculationMethod
private int CalculatePower(int hours,int mins)
{
//do calculation
int calc = 0;
return calc;
}
然后,也许在选择组合框中的值后,您可以点击按钮并点击其事件。将组合框的值转换为整数RS因为那的方法需要的参数,做你的计算
private void button1_Click(object sender, EventArgs e)
{
//set label's text to the calculated power
//convert the values of the comboboxes to integers so that you could do calculations with them
//and because the calculatepower method is expecting ints
//tostring at end to set labels text to a string
label1.Text = CalculatePower(Convert.ToInt32(this.hoursComboBox.SelectedValue), Convert.ToInt32(this.minsComboBox.SelectedValue)).ToString();
}
也许这给你如何完成你正在尝试做
我认为你的CalculationMethod应该返回小时+(分钟/ 60); –
我完全同意,但我把计算逻辑留给了他,因为他的问题更多地是如何从他的组合框中获取值 – mjmendes
我觉得最难的是要转换为数字的一个想法从基于60的分钟数基于10号 这里是一个全球性的解决方案:
Dictionary<string, double> dictionaryValues = new Dictionary<string, double>();
private void Form1_Load(object sender, EventArgs e)
{
comboBoxApplicances.Items.Add("Air conditioning");
comboBoxApplicances.Items.Add("Attic fan");
comboBoxApplicances.Items.Add("Ceiling fan");
comboBoxApplicances.Items.Add("Dishwasher");
comboBoxApplicances.SelectedIndex = 0;
dictionaryValues.Add("Air conditioning", 0);
dictionaryValues.Add("Attic fan", 0);
dictionaryValues.Add("Ceiling fan", 0);
dictionaryValues.Add("Dishwasher", 0);
for (int i = 0; i < 24; i++)
{
comboBoxHours.Items.Add(i < 10 ? "0" + i : i.ToString()); // add 0 for i < 10
}
comboBoxHours.SelectedIndex = 0;
comboBoxMinutes.Items.Add("00");
comboBoxMinutes.Items.Add("15");
comboBoxMinutes.Items.Add("30");
comboBoxMinutes.Items.Add("45");
comboBoxMinutes.SelectedIndex = 0;
}
private void buttonCompute_Click(object sender, EventArgs e)
{
// adding value to the selected appliance
dictionaryValues[comboBoxApplicances.SelectedItem.ToString()] +=
GetHoursMinutes(comboBoxHours.SelectedItem.ToString(),
comboBoxMinutes.SelectedItem.ToString());
labelCurrentApplicance.Text = dictionaryValues[comboBoxApplicances.SelectedItem.ToString()].ToString();
}
private double GetHoursMinutes(string hours, string minutes)
{
double result = 0;
double minutesB60 = double.Parse(minutes);
double minutesB10 = (minutesB60/60);
result = double.Parse(hours) + minutesB10;
return result;
}
喜迈克尔,我看你是新来的,欢迎!首先,你的回答非常含糊,我们需要更多的信息和细节,例如这个winforms或asp.net?其次,您可以提供您正在使用的相关代码以及您试图解决它的尝试,例如变量和组合框。然后,我们可以给你一个更明确的答案:) – Matchbox2093
_ [我如何问一个好问题?](http://stackoverflow.com/help/how-to-ask)_ – MickyD
你如何填充组合框,是它将数据绑定到数据集?如何除了其他人的建议,我们可能能够帮助你的所有信息 –