C# WinForms 逐个读取组合框项



让我快速浏览一下我的工作。我正在研究Winforms。

我想做什么:我想选择一个文件并根据组合框中的选定值从中提取特定段落。

我做了什么:

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

一切正常。我无法做的是,从组合框中选择第一项并完成复制粘贴操作后,我无法选择下一项。它只是转到"已找到"并抛出错误消息框。我不想自动选择组合框项目。相反,我希望它等到用户从组合框中选择另一个键,并根据键选择提取下一段

我确实意识到我错过了一些东西。但我不知道是什么!我应该怎么做,以便用户可以在我从消息框中单击"是"时选择其他组合框项?我可以使用线程概念并使用 Sleep(( 等待几秒钟的用户输入,但我认为这不可行。

有人有其他想法吗?任何帮助表示赞赏。提前谢谢。

(考虑到您的代码(为此,您必须在阅读后更改所选项目:

key = CmboBox.SelectedItem.ToString();
if(CmboBox.SelectedIndex < ComboBox.Items.Length -1)
CmboBox.SelectedIndex;

但是,使用CmboBox.SelectedItem并逐个更改以获取其项目并不是一个好主意。您可以遍历所有项目。一个简单的 for 循环将是最好的选择,尽管可能还有其他方法,如 Linq,...

for(int i=0; i<ComboBox.Items.Length;i++)
{
key = ComboBox.Items[i].ToString();
//rest of your code
}

更新考虑您的评论:

DialogResult current = DialogResult.No;
do
{
key = CmboBox.SelectedItem.ToString();
DialogResult dialogResult = MessageBox.Show("Select next key", "Continue?", MessageBoxButtons.YesNo);
if (!keys.Contains(key))
{
if (n < keys.Length)
keys[n++] = key;
}
else
{
MessageBox.Show("You have already added this Key","Error");
}
}while(dialogResult == DialogResult.Yes);

相关内容

最新更新