一尘不染

如何将列表绑定到dataGridView?

c#

我似乎在圈子里跑来跑去,并且在过去的几个小时中一直在这样做。

我想从字符串数组中填充一个datagridview。我已经读过它不可能直接实现,我需要创建一个自定义类型来将字符串作为公共属性保存。所以我上了一堂课:

public class FileName
    {
        private string _value;

        public FileName(string pValue)
        {
            _value = pValue;
        }

        public string Value
        {
            get 
            {
                return _value;
            }
            set { _value = value; }
        }
    }

这是容器类,它只是具有带有字符串值的属性。当我将其数据源绑定到列表时,我现在想要的只是该字符串出现在datagridview中。

我也有此方法BindGrid(),我想用它填充datagridview。这里是:

    private void BindGrid()
    {
        gvFilesOnServer.AutoGenerateColumns = false;

        //create the column programatically
        DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn();
        DataGridViewCell cell = new DataGridViewTextBoxCell();
        colFileName.CellTemplate = cell; colFileName.Name = "Value";
        colFileName.HeaderText = "File Name";
        colFileName.ValueType = typeof(FileName);

        //add the column to the datagridview
        gvFilesOnServer.Columns.Add(colFileName);

        //fill the string array
        string[] filelist = GetFileListOnWebServer();

        //try making a List<FileName> from that array
        List<FileName> filenamesList = new List<FileName>(filelist.Length);
        for (int i = 0; i < filelist.Length; i++)
        {
            filenamesList.Add(new FileName(filelist[i].ToString()));
        }

        //try making a bindingsource
        BindingSource bs = new BindingSource();
        bs.DataSource = typeof(FileName);
        foreach (FileName fn in filenamesList)
        {
            bs.Add(fn);
        }
        gvFilesOnServer.DataSource = bs;
    }

最后,问题是:字符串数组填充成功,列表创建成功,但是我在datagridview中得到了一个空列。我也直接尝试了datasource = list
<>,而不是= bindingsource,还是一无所获。

我非常感谢您的建议,这使我发疯。


阅读 187

收藏
2020-05-19

共1个答案

一尘不染

使用BindingList并设置列的DataPropertyName
-Property。

请尝试以下操作:

...
private void BindGrid()
{
    gvFilesOnServer.AutoGenerateColumns = false;

    //create the column programatically
    DataGridViewCell cell = new DataGridViewTextBoxCell();
    DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()
    {
        CellTemplate = cell, 
        Name = "Value",
        HeaderText = "File Name",
        DataPropertyName = "Value" // Tell the column which property of FileName it should use
     };

    gvFilesOnServer.Columns.Add(colFileName);

    var filelist = GetFileListOnWebServer().ToList();
    var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList

    //Bind BindingList directly to the DataGrid, no need of BindingSource
    gvFilesOnServer.DataSource = filenamesList 
}
2020-05-19