how to bind datatable to datagridview in c#

前端 未结 7 691
面向向阳花
面向向阳花 2020-11-27 20:50

I need to bind my DataTable to my DataGridView. i do this:

        DTable = new DataTable();
        SBind = new BindingSou         


        
7条回答
  •  旧时难觅i
    2020-11-27 21:30

    // I built my datatable first, and populated it, columns, rows and all. //Then, once the datatable is functional, do the following to bind it to the DGV. NOTE: the DGV's AutoGenerateColumns property must be 'true' for this example, or the "assigning" of column names from datatable to dgv will not work. I also "added" my datatable to a dataset previously, but I don't think that is necessary.

     BindingSource SBind = new BindingSource();
     SBind.DataSource = dtSourceData;
    
     ADGView1.AutoGenerateColumns = true;  //must be "true" here
     ADGView1.Columns.Clear();
     ADGView1.DataSource = SBind;
    
     //set DGV's column names and headings from the Datatable properties
     for (int i = 0; i < ADGView1.Columns.Count; i++)
     {
           ADGView1.Columns[i].DataPropertyName = dtSourceData.Columns[i].ColumnName;
           ADGView1.Columns[i].HeaderText = dtSourceData.Columns[i].Caption;
     }
     ADGView1.Enabled = true;
     ADGView1.Refresh();
    

提交回复
热议问题