【发布时间】:2018-10-16 07:39:11
【问题描述】:
让我简要介绍一下我的工作。我正在开发 Winform。
我想做什么:我想选择一个文件,并根据我在 combobox 中的选定值从中提取特定段落。
我做了什么:
private void ExtrctBtn_Click(object sender, EventArgs e)
{
//I have another button to select file
string sourceFile = "", resultFile = "";
if (sourceFile == null || !(File.Exists(sourceFile)))
{
MessageBox.Show("Please select a file to continue", "File Error");
}
else
{
sw = Stopwatch.StartNew(); //start the timer
ExtrctBtn.Enabled = false;
resultFile = Path.Combine(Path.GetDirectoryName(sourceFile), "Results_" + DateTime.Now.ToString("yyMMddHHmmss") + ".txt");
WriteReport(resultFile);
sw.Stop(); //stop the timer
}
private void WriteReport(string dest)
{
try
{
int n = 0;
string key = "";
string[] keys = new string[10];
Found:
key = CmboBox.SelectedItem.ToString();
if (!keys.Contains(key))
{
//copy the required data from source file to result file
if (n < keys.Length)
keys[n++] = key;
DialogResult dialogResult = MessageBox.Show("Select next key", "Continue?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
goto Found;
}
else //if (dialogResult == DialogResult.No)
{
goto Finish;
}
}
else
{
MessageBox.Show("You have already added this Key","Error");
}
Finish:
SaveFile();
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "Exception");
}
}
一切正常。 我无法做的是,在我从组合框中选择第一项并完成复制粘贴操作后,我无法选择下一项。它只是转到 Found 并抛出错误消息框。我不想自动选择组合框项目。相反,我希望它等到用户从组合框中选择另一个键并根据键选择提取下一段。
我确实意识到我错过了一些东西。但我不知道是什么! 当我从消息框中单击“是”时,我应该怎么做才能让用户选择其他组合框项目?我可以使用线程概念并使用 Sleep() 等待几秒钟供用户输入,但我认为它不可行。
有人有其他想法吗?任何帮助表示赞赏。提前致谢。
【问题讨论】:
-
非常重要:不要使用
goto:它只会让你的代码很难阅读和维护。 -
您永远不会填充
keys,因此不包含将始终为真。 -
你知道你可以把你的整个对象放在组合框中,对吧?它只需要一个 ToString 函数。然后你只需将
SelectedItem转换回原来的类型就可以了。 -
@Richard:我用
if (n < keys.Length) keys[n++] = key;填充它 -
@Nyerguds:是的,我知道。我有另一个功能可以将项目添加到组合框并且工作正常。没问题。