我是C#的新手,尽管去年我确实学习了Java的四分之一。我的作业明天要交,所以这是我的问题。我编写了一个小程序示例,希望可以得到想要的东西。我想知道,我如何看待listBox并说,例如,如果选择了项目Soccer,则做一件事,但是如果选择了其他任何东西,则做另一件事?我将上传一段不执行应做的代码,大家都可以称我为愚蠢的人,然后给我答案。
private void submitButton_Click(object sender, EventArgs e)
{
string best;
best = namesListBox.SelectedItem.ToString();
if ((string)namesListBox.SelectedItem == "Soccer")
{
MessageBox.Show("Fried chicken, don't let that bird die in vain.");
}
else
{
MessageBox.Show("Long long ago, in the land of the Hobbit...");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
Close();
}
}
}
每次运行此代码时,我总是很久以前……。这不是我想要看到的。任何帮助将不胜感激,我将放弃这个程序。这不是实际的程序,它要复杂得多,我只是制作了这个程序来演示我的问题……在此先感谢
尤里,
看起来您正在将所选项目附加到字符串中。我觉得这可能是问题所在。
您究竟将字符串“ best”用作什么?您定义了它,但是在您的示例中未使用它。
这是你想要的?尝试使用ToString()方法,并对其进行修剪,以使空格不会抛出您的代码:
string selectedItem = namesListBox.SelectedItem.ToString().Trim();
if (selectedItem == "Soccer")
MessageBox.Show("Soccer is selected.");
else
MessageBox.Show("NOT SELECTED");
也许是套管错误?如果您不想担心大写或小写,请尝试在字符串中附加.ToLower():
string selectedItem = namesListBox.SelectedItem.ToString().Trim().ToLower();
if (selectedItem == "Soccer".ToLower())
// Handle code accordingly.
else
// Handle accordingly.
您还可以在ListBox中搜索字符串,然后找出其位置。然后确定用户是否选择了该特定项目:
int selIndex = namesListBox.FindString("Soccer");
这将返回其中包含单词“ Soccer”的第一项的位置的从零开始的索引。
现在处理选定的索引:
if (namesListBox.SelectedIndex != -1 &&
namesListBox.SelectedIndex == selIndex)
MessageBox.Show("First item containing \"Soccer\" is selected.");
else
MessageBox.Show("First item containing \"Soccer\" is not selected.");
您很有可能使用的是ListView对象,而不是实际的ListBox。在这种情况下,您将不得不采用其他方法。此示例仍然使用您的ListBox名称:
// This assumes that you cannot select multiple items, and that you
// only have one column in your ListView.
string selectedItem = namesListBox.SelectedItems[0].SubItems[0].Text;
if (selectedItem.Trim() == "Soccer") // Continue as before...
这对您的项目有用吗?
编辑:等等。您是否要在评估之前将所选项目更改为“最佳”?
如果是这样,请执行以下操作:
int selIndex = namesListBox.SelectedIndex;
namesListBox.Items.RemoveAt(selIndex);
namesListBox.Items.Insert(selIndex, "best");
编辑:
确保包括不处理任何选择的代码:
// Will not execute block of code if nothing is selected.
if (namesListBox.SelectedIndex == -1)
{
MessageBox.Show("No item is selected.");
return;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句