【发布时间】:2021-04-29 12:56:24
【问题描述】:
我有一个正在读取 CSV 文件的 C# 程序。使用 StreamReader,我用 CSV 的内容填充组合框。 CSV 包含 4 个字段。我只想在所选行中显示第一个值。然后我想将其他字段中的 2 个传递给另一个进程(我正在尝试按位置映射网络打印机)。这是我阅读 CSV 的部分。
try
{
// Open the CSV file to read
StreamReader sr = new StreamReader(printerList);
String currentline = sr.ReadLine();
while (!sr.EndOfStream)
{
currentline = sr.ReadLine();
comboBoxPrinterList.Items.Add(currentline);
}
}
catch (Exception ex)
{
// Display an error message if the file cannot be read
MessageBox.Show("The file could not be read" + ex.Message);
}
这非常有效。唯一的问题是这条线太长了,不可读。最终用户只需选择位置,即第一个字段。
为了测试,我使用这段代码来显示结果
int selectedIndex = comboBoxPrinterList.SelectedIndex;
Object selectedItem = comboBoxPrinterList.SelectedItem;
MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
有没有办法只显示组合框中的第一个字段,但仍然使用从组合框控件传递的索引号?我正在考虑创建一个仅包含第一个字段的数组,但不知道如何引用该数组和组合框索引。
任何帮助都非常感谢....
【问题讨论】:
-
这能回答你的问题吗? Parsing CSV files in C#, with header
-
这与我使用 StreamReader 所做的非常相似。 rbrettj的回答更符合我想做的事情。