Sealer_05
Sealer_05

Reputation: 5576

How to format datagridview when filling with linq2sql query

I am looking to format the datagridview so I can hide and format certain column headers. The problem is I cant use the built in winforms dgv formatting because I am filling the grid from a straight linq query and not binding the table with the built in wizard. Here is my code to fill the table. How can I format the headers on the grid? Thanks!

var search = from s in db.trips
             orderby s.tripNo descending
             select s;

    dgvTripGrid.DataSource = search;

Upvotes: 1

Views: 914

Answers (1)

ΩmegaMan
ΩmegaMan

Reputation: 31721

Create a dynamic entity with the column (header) names which should be displayed and bind it here is an example:

BindingSource bindingSource1= new BindingSource();
private void LoadGrid()
{
    List<Data> dataListing = new List<Data>()
    {
        new Data() { Name = "Jabberwocky", Operation="Read", DateStart= DateTime.Now.AddDays(-2), DateEnd = DateTime.Now.AddDays(-2), Description="Process Started No errors"},
        new Data() { Name = "Space", Operation="Write", DateStart= DateTime.Now.AddDays(-2), DateEnd = DateTime.Now.AddDays(-1), Description="Final process remote allocation of 3000 items to main buffer."},
        new Data() { Name = "Stock Purchase", Operation="DataWarehousing", DateStart= DateTime.Now, DateEnd = DateTime.Now, Description="Shared data transport."}
    };

    var items = from dta in dataListing
        select new
        {
           OperationName = dta.Name,
           Start         = dta.DateStart.ToShortDateString(),
           End           = dta.DateEnd.ToShortDateString(),
           Operation     = dta.Operation,
           Description   = dta.Description
         };

    bindingSource1.DataSource = items;
    dataGridView1.DataSource  = bindingSource1;

    // Grid attributes
    dataGridView1.BorderStyle         = BorderStyle.Fixed3D;
    dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

}

I show this example on my blog C# Linq How To Load a Winform Control Using Dynamic Linq entitites

Upvotes: 2

Related Questions