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

前端 未结 6 524
眼角桃花
眼角桃花 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:13

    We can create a new DataTable with the required Columns and add rows to it from the Dataset. Then we can initialize the DataGrid with the Newly Created DataTable.

    dt = new DataTable();          
    dt_Property.Columns.Add("Field1");
    dt_Property.Columns.Add("Field2");
    int i = 0;
    DataRow row = null;
    foreach (DataRow r in ds.Tables[0].Rows)
    {               
        row = dt.NewRow();                    
        row["Field1"] = ds.Tables[0].Rows[i][1];
        row["Field2"] = ds.Tables[0].Rows[i][2];
        dt_Property.Rows.Add(row);   
        i = i + 1;
    }
    
    dataGridView1.DataSource = dt;
    

提交回复
热议问题