无法使用WinForm应用程序中的BindingList将数据绑定到DataGridView

时间:2021-10-08 14:47:04

I am reading data from excel file (.csv) and storing that data to List<String>. I want to display this data to DataGridView but for some reason I am seeing total length of String in Grid.

我正在从excel文件(.csv)读取数据并将该数据存储到List 。我想将这些数据显示给DataGridView,但由于某种原因,我看到Grid中String的总长度。

Following is my code :

以下是我的代码:

CODE:

private void btnImportFile_Click(object sender, EventArgs e)
{
    OpenFileDialog dialog = new OpenFileDialog();
    dialog.Filter = "CSV (Comma delimited) (*.csv)|*.csv";
    dialog.FilterIndex = 1;
    dialog.Multiselect = false;

    var userClickedOK = dialog.ShowDialog();

    if (userClickedOK.ToString().Equals("OK"))
    {
        this.lblImportedFileName.Text = dialog.SafeFileName;

        System.IO.Stream fileStream = dialog.OpenFile();

        using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
        {
            var list = new List<String>();
            var line = String.Empty;

            while ((line = reader.ReadLine()) != null) //Reading value and adding it to the list.
            {
                list.Add(line);

            }

            BindingList<String> view = new BindingList<String>(list);
            this.gridExcelResults.DataSource = view; // Binding list to grid

            //Also tried
            this.gridExcelResults.DataSource = list; // This also gives me same result.

        }
    }
}

OUTPUT:

无法使用WinForm应用程序中的BindingList将数据绑定到DataGridView

EXCEL DATA:

无法使用WinForm应用程序中的BindingList将数据绑定到DataGridView

EXPECTED RESULT:

I just want to display these three fields on Grid. What am I doing wrong here?

我只想在Grid上显示这三个字段。我在这做错了什么?

1 个解决方案

#1


3  

See this question: How to bind a List<string> to a DataGridView control?

看到这个问题:如何将List 绑定到DataGridView控件?

In your case you are using a BindingList<string> but the logic is the same. The DataGridView is looking for object properties to bind, String however, only has the property length.

在您的情况下,您使用的是BindingList ,但逻辑是相同的。 DataGridView正在寻找要绑定的对象属性,但是,String只有属性长度。

#1


3  

See this question: How to bind a List<string> to a DataGridView control?

看到这个问题:如何将List 绑定到DataGridView控件?

In your case you are using a BindingList<string> but the logic is the same. The DataGridView is looking for object properties to bind, String however, only has the property length.

在您的情况下,您使用的是BindingList ,但逻辑是相同的。 DataGridView正在寻找要绑定的对象属性,但是,String只有属性长度。