How to Bind specific Columns of a datatable to a DataGridView?

前端 未结 6 493
眼角桃花
眼角桃花 2020-12-09 11:43

My DataTable has three columns fetched from a database, while I need to bind only two columns of it to a DataGridView. Can you please help me with

6条回答
  •  独厮守ぢ
    2020-12-09 12:03

    Create the columns for the DataGridView yourself. Try something like this.

    DataGridView dataGridView1 = new DataGridView();
    BindingSource bindingSource1 = new BindingSource();
    
    dataGridView1.ColumnCount = 2;
    
    dataGridView1.Columns[0].Name = "Field1";
    dataGridView1.Columns[0].DataPropertyName = "Field1";
    dataGridView1.Columns[1].Name = "Field2";
    dataGridView1.Columns[1].DataPropertyName = "Field2";
    
    bindingSource1.DataSource = GetDataTable();
    dataGridView1.DataSource = bindingSource1;
    

提交回复
热议问题