How to show only certain columns in a DataGridView with custom objects

后端 未结 8 1529
有刺的猬
有刺的猬 2020-12-29 07:18

I have a DataGridView and I need to add custom objects to it. Consider the following code:

DataGridView grid = new DataGridView();
grid.DataSource = objects         


        
8条回答
  •  别那么骄傲
    2020-12-29 08:04

    You can do something like this.

    To display only particluar columns in a DataGridView first you take the data in a DataTable like this.

    String query="Your query to dispplay columns from the database";
    SqlCommand cmd=new SqlCommand(query,con); //con is your Connection String
    con.Open();
    DataTable dt=new DataTable();
    SqlDataAdapter da=new SqlDataAdapter(cmd);
    da.Fill(dt); //Now this DataTable is having all the columns lets say
    /* Now take another temporary DataTable to display only particular columns*/
    DataTable tempDT=new DataTable();
    tempDT=dt.DefaultView.ToTable(true,"Your column name","your column name");
    //Now bind this to DataGridView
    grid.DataSource=tempDT;
    con.Close();
    

    I know this is a quite long process.Those who go for the performance might not like this. :P

    But i think it works fine.

提交回复
热议问题