imu*_*ion 3 c# visual-studio-2010
简单的问题:我正在检查组合框是否已使用string.IsNullOrEmpty(). 问题是,即使选择了 ,也会出现错误消息。我究竟做错了什么?
这是我的代码:
private void button1Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(comboBox1.SelectedText))//here should skip to else - but doesn't
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
if (comboBox1.SelectedText == "Currency")
{
double input = Convert.ToDouble(textBox1.Text);
if (!string.IsNullOrEmpty(comboBox2.SelectedText))
{
string type = comboBox2.SelectedText;
double result = convertCurrency(type, input);
if (result != -1)
{
label1.Text = Convert.ToString(result);
}
}
else
{
MessageBox.Show("You must select a conversion type", "Error");
}
}
else
{
MessageBox.Show("curency");
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:这是我的第二个 C# 程序 - 所以如果我很愚蠢,请不要对我大喊大叫。
通常有一些观察/建议。
首先,您使用字符串值并基于这些值建立逻辑,您可能需要考虑使用 Enum 并将其所有值绑定到组合框。然后使用 SelectedItem 属性并将其与 Enum 进行比较。
当没有选择任何项目时,SelectedItem 将返回 NULL,另一个选项是使用 SelectedIndex,当没有选择任何项目时将返回 -1。
所以使用 SelectedIndex 它将变成这样;
if (comboBox1.SelectedIndex == -1)//Nothing selected
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
//Do Magic
}
Run Code Online (Sandbox Code Playgroud)
通常,只有在不可能进行诸如 int 比较或更好的 enum 比较之类的“强”比较时,才应使用字符串比较。(也许只是我一个人,但字符串经常变化,对于这类东西来说很可怕。)
对于枚举建议,可能查看这些链接之一;
是否可以将项目从 Enum 加载到 .NET 3.5 中的 ComboBox?
我不确定在 WPF 中使用哪个 .NET 版本和作为绑定的东西比在旧的 Windows 窗体中容易得多(在我看来)。