C# 组合框(C、WPF)中选择的项目错误
组合框C、WPF中选择的项目错误 我有一个组合框和一个文本框。当我在组合框中选择一个项目html文件时,我想将内容添加到我的文本框中。以下是我到目前为止得到的信息:C# 组合框(C、WPF)中选择的项目错误,c#,wpf,combobox,textbox,fileinfo,C#,Wpf,Combobox,Textbox,Fileinfo,组合框C、WPF中选择的项目错误 我有一个组合框和一个文本框。当我在组合框中选择一个项目html文件时,我想将内容添加到我的文本框中。以下是我到目前为止得到的信息: public void SetDataPoolToComboBox() { comboBox_DataPool.Items.Clear(); comboBox_DataPool.Items.Add("Please choose a file..."); comboBox_Da
public void SetDataPoolToComboBox()
{
comboBox_DataPool.Items.Clear();
comboBox_DataPool.Items.Add("Please choose a file...");
comboBox_DataPool.SelectedIndex = 0;
if (true == CheckPath())
{
foreach (string s in Directory.GetFiles(pathTexts, "*.html"))
{
comboBox_DataPool.Items.Add(Path.GetFileNameWithoutExtension(s));
}
}
}
public void comboBox_DataPool_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SetContentToTextBox();
}
public void SetContentToTextBox()
{
if (true == CheckPath())
{
FileInfo[] fileInfo = directoryInfo.GetFiles("*.html");
if (fileInfo.Length > 0)
{
if (comboBox_DataPool.Text == "Please choose a file..." || comboBox_DataPool.Text == "")
{
textBox_Text.Text = string.Empty;
}
else
{
StreamReader sr = new StreamReader(fileInfo[comboBox_DataPool.SelectedIndex].FullName, Encoding.UTF8);
textBox_Text.Text = sr.ReadToEnd();
sr.Close();
}
}
}
}
问题:当我选择第二项时,会显示第三项的内容。每次都会发生同样的情况-我选择哪一项并不重要。当我选择最后一项时,应用程序被踢出:错误:索引超出范围 问题是您添加了一个伪字符串,请选择一个文件。。。在组合框的items集合中,然后添加fileInfos集合项 因此,如果选择,索引将是1,它将指向集合中的第0项。所以,当从fileInfo集合获取项时,您需要从comboBox_DataPool.SelectedIndex-1索引位置获取项 改变
StreamReader sr = new StreamReader(fileInfo[comboBox_DataPool.SelectedIndex]
.FullName, Encoding.UTF8);
到
它似乎起作用了。不幸的是,当我单击第一项“请选择一个文件…”时,它会引发相同的异常。第0个索引不应通过else语句。它应该在第一个条件下处理。不确定为什么不能,但可以像这样检查SelectedIndex,而不是检查字符串-如果comboBox\u DataPool.SelectedIndex==0{textBox\u Text.Text=string.Empty;}。
StreamReader sr = new StreamReader(fileInfo[comboBox_DataPool.SelectedIndex - 1]
.FullName, Encoding.UTF8);