如何将列表绑定到dataGridView?

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


我想从字符串数组中填充一个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,还是一无所获。


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


慕斯王
浏览 513回答 3
3回答

拉丁的传说

使用BindingList并设置列的DataPropertyName -Property。请尝试以下操作:...private void BindGrid(){&nbsp; &nbsp; gvFilesOnServer.AutoGenerateColumns = false;&nbsp; &nbsp; //create the column programatically&nbsp; &nbsp; DataGridViewCell cell = new DataGridViewTextBoxCell();&nbsp; &nbsp; DataGridViewTextBoxColumn colFileName = new DataGridViewTextBoxColumn()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; CellTemplate = cell,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Name = "Value",&nbsp; &nbsp; &nbsp; &nbsp; HeaderText = "File Name",&nbsp; &nbsp; &nbsp; &nbsp; DataPropertyName = "Value" // Tell the column which property of FileName it should use&nbsp; &nbsp; &nbsp;};&nbsp; &nbsp; gvFilesOnServer.Columns.Add(colFileName);&nbsp; &nbsp; var filelist = GetFileListOnWebServer().ToList();&nbsp; &nbsp; var filenamesList = new BindingList<FileName>(filelist); // <-- BindingList&nbsp; &nbsp; //Bind BindingList directly to the DataGrid, no need of BindingSource&nbsp; &nbsp; gvFilesOnServ
打开App,查看更多内容
随时随地看视频慕课网APP