How do I display only certain columns from a data table?

36,810

Solution 1

Ignore the fact that you have more data than you need. Set AutoGenerateColumns to false. Create BoundColumns for a3 and a4.

Solution 2

I'd recommend reading this article from 4GuysFromRolla for anyone who needs a good understanding of the DataGrid Web Control.

Note: Since this question is already answered. I want to clarify what needs to be done, just in case anyone else is wondering.

DataSet ds;

//Get Data
using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "GetMyData";
        command.CommandType = CommandType.StoredProcedure;

        ds = connection.ExecuteDataSet();
    }
if(ds !=null && ds.Tables.Count > 0)
{
    dg.DataSource = ds.Tables[0];
    // disable autogeneration of columns
    dg.AutoGenerateColumns = false;
    //Hide unecessary columns
    dg.Columns["a3"].Visible = false;
    dg.Columns["a4"].Visible = false;
}

Solution 3

I'd bind the whole table, then set up visibility of the coulmns as follows

dgvMain.Columns[ColumnA3_Name].Visible = true;
dgvMain.Columns[ColumnA1_Name].Visible = false;

Solution 4

Hi Following code can be used

//It represent name of column for which you want to select records
string[] selectedColumns = new[] { "a3", "a4" }; 

DataTable tableWithSelectedColumns = new DataView(dataset.Table["A"]).ToTable(false,  selectedColumns);

I tried this and it works.

Share:
36,810
Adyt
Author by

Adyt

Maybe part of "programming skill" is being able to "soullessly" or "mindlessly" program away for something you hold no interest in. In that case I lack "programming skill"

Updated on October 08, 2020

Comments

  • Adyt
    Adyt over 3 years

    I'm using a web service that returns a dataset. in this dataset there are 5 table, let's say table A, B, C, D, E. I use table A.

    So

    DataTable dt = new DataTable()
    dt = dataset.Table["A"]
    

    Now in this datatable there are columns a1,a2,a3,a4,a5,a6,a7.

    Let's say I only want to get columns a3 and a4 then bind it to my datagrid.

    How do I do this?