gpt4 book ai didi

c# - 验证组合框的 SelectedText 属性是否为空总是失败

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:58 25 4
gpt4 key购买 nike

简单问题:我正在检查组合框是否已使用 string.IsNullOrEmpty() 选择了一个项目。问题是,即使选择了 is,也会出现错误消息。我做错了什么?

这是我的代码:

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");
}
}
}

注意:这是我的第二个 C# 程序 - 如果我很愚蠢,请不要对我大喊大叫。

最佳答案

通常是一些观察/建议。

首先,您使用的是字符串值并基于这些值的逻辑,您可能想要研究使用 Enum 并将其所有值绑定(bind)到组合框。然后使用 SelectedItem 属性并将其与枚举进行比较。

当没有选择任何项目时,SelectedItem 将返回 NULL,另一个选项是使用 SelectedIndex,当没有选择任何项目时它将返回 -1。

所以对于 SelectedIndex,它会变成类似的东西;

if (comboBox1.SelectedIndex == -1)//Nothing selected
{
MessageBox.Show("You must select a conversion type", "Error");
}
else
{
//Do Magic
}

一般来说,只有在诸如 int 比较或更好的 enum 比较之类的“强”比较不可能时才应使用字符串比较。 (也许只有我一个人是这样,但字符串经常更改并且对这类东西来说只是可怕的。)

对于枚举建议,可以查看这些链接之一;

Binding an enum to a WinForms combo box, and then setting it

Load values of enum type into a combobox

Is it possible to load items from an Enum to a ComboBox in .NET 3.5?

Binding a ComboBox to an Enumeration

我不确定您使用的是哪个 .NET 版本和东西,因为在 WPF 中绑定(bind)比在旧的 Windows 窗体中绑定(bind)要容易得多(在我看来)。

关于c# - 验证组合框的 SelectedText 属性是否为空总是失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18122484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com