【问题标题】:listBox not displaying desired results from a dataSource with C#列表框不显示来自 C# 数据源的所需结果
【发布时间】:2017-10-18 16:40:44
【问题描述】:

我下面的代码在运行时显示:

string filePath = @"C:\Users\Jim\Desktop\us-500.csv";
StreamReader sr = new StreamReader(filePath);
var lines = new List<string[]>();
int Row = 0;
while (!sr.EndOfStream)
{
    string[] Line = sr.ReadLine().Split(',');
    lines.Add(Line);
    Row++;
}

var data = lines.ToArray();

bindingSource1.DataSource = data;
listBox1.DataSource = bindingSource1;

如何让它向我显示如下所示的每一行字段?

【问题讨论】:

  • 您声明了一个“数组”列表,但您想要的输出不是数组,而是列表中的单个字符串。也许你只想要var data = lines[0].ToArray();
  • 如果这是我需要的唯一行,那就太好了,但我想使用 bindingNavagator 浏览 CSV 文件。但感谢您的意见。

标签: c# listbox datasource


【解决方案1】:

在使用数据源时,数组不太好用。避免将列表转换为数组,因为这不是必需的。

bindingSource1.DataSource = lines;
bindingNavigator1.BindingSource = bindingSource1;

然后尝试使用 BindingSource 的 PositionChanged 事件为 ListBox 设置 DataSource:

void bindingSource1_PositionChanged(object sender, EventArgs e) {
  var items = bindingSource1.DataSource as List<string[]>;
  if (items != null && bindingSource1.Position >= 0 && 
                       bindingSource1.Position < items.Count ) {
    listBox1.DataSource = items[bindingSource1.Position];
  }
}

【讨论】:

    【解决方案2】:

    根据您的要求,我认为可以做到。

    1. 阅读每一行
    2. 将每一行分成多个字段
    3. 将每个字段添加到数据源
    4. 绑定到数据源

    .

    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using System.IO;
    
    namespace PopulateListBoxFromCSV_46815162
    {
    
        public partial class Form1 : Form
        {
            ListBox lstbx = new ListBox();
            public Form1()
            {
                InitializeComponent();
                initializeListBox();
                //fillTheListBox(@"C:\temp\myfile.csv");
                fillTheListBox(@"C:\temp\myfile.csv", true);
            }
    
            /// <summary>
            /// Lets say you want to show field value only
            /// </summary>
            /// <param name="filePath"></param>
            private void fillTheListBox(string filePath)
            {
    
                List<string> results = new List<string>();
                string currentLine = string.Empty;
                using (StreamReader sr = new StreamReader(filePath))
                {
                    while ((currentLine = sr.ReadLine()) != null)//for as long as there is something to read
                    {
                        foreach (string item in currentLine.Split(','))//split the current line into multiple "fields"
                        {
                            results.Add(item);//add each individual field to the dataSource to create your 1FieldPerLine visual
                        }
                    }
                }
                lstbx.DataSource = results;//bind your datasource
            }
    
    
            /// <summary>
            /// Lets say you wanted to show "Header" : "FieldValue"
            /// </summary>
            /// <param name="filePath"></param>
            /// <param name="ShowHeader"></param>
            private void fillTheListBox(string filePath, bool ShowHeader)
            {
                List<string> headerLine = new List<string>();
                List<string> results = new List<string>();
                int whichLineAmIon = 0;
                string currentLine = string.Empty;
                using (StreamReader sr = new StreamReader(filePath))
                {
                    while ((currentLine = sr.ReadLine()) != null)//for as long as there is something to read
                    {
                        string[] splitted = currentLine.Split(',');//split the line into fields
                        for (int i = 0; i < splitted.Length; i++)
                        {
                            if (whichLineAmIon == 0)//then we are on the header line
                            {
                                headerLine.Add(splitted[i]);
                            }
                            else
                            {
                                results.Add(headerLine[i] + " : " + splitted[i]);//add each individual field to the dataSource to create your 1FieldPerLine visual
                            }
                        }
                        whichLineAmIon++;
                    }
                }
    
                lstbx.DataSource = results;//bind your datasource
            }
    
            private void initializeListBox()
            {
                lstbx.Dock = DockStyle.Fill;
                lstbx.BackColor = Color.Azure;
                this.Controls.Add(lstbx);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      这里 string[] Line = sr.ReadLine().Split(','); lines.Add(Line);

      您添加的是字符串数组而不是字符串。

      为了解决这个问题,你必须做其他的事情,像这样。

      string[] Line = sr.ReadLine().Split(',');
      for (int i = 0; i < Line.Length ; i++)
      {
          lines.Add(Line[i]);
          Row++;
      }
      

      【讨论】:

        【解决方案4】:

        您的列表框仅显示对象。将其绑定到 DisplayMemberPath 属性。

        【讨论】:

        • ListBox 以线性方式显示。 DataSource 中的每个条目将在 ListBox 中生成 1 行。由于他当前将整行添加为数据源中的 1 个条目,因此每个 ListBox 行将代表 1 whole CSV 行。这不是他想要的。根据截图,他想把每一行分解成单独的字段,这样每个字段就可以显示在自己的行上。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多