mrvinent mrvinent - 27 days ago 8
C# Question

DevExpress GridControl mainview not showing information

I have a GridControl from Devexpress and I fill the control with a DataRow object. The row is added to the grid but the cells are empty. Here's the code:

DataTable dt = new DataTable();
dt.Columns.Add("Descripcion");
dt.Columns.Add("Cantidad");
dt.Columns.Add("Importe");
gridControl1.DataSource = dt;

clsLineaTicket newLn = new clsLineaTicket("Gin Tonic Beefeater", "1", "9,20");
DataRow dr = dt.NewRow();
dr[0] = newLn.strDescripcion;
dr[1] = newLn.strCantidad;
dr[2] = newLn.strImporte;
dt.Rows.Add(dr);
gridControl1.DataSource = dt;


The code is pretty simple, any idea why is not working? Thank you.

Answer

To solve your problem you should set the FieldNames of your GridColumns to the ColumnNames of your DataTable.

But i would strongly recommend you to use List<clsLineaTicket> instead of convert this to DataTable.

At first you already got an object and the Grid can handle this pretty well. So converting this to DataRows seems to be unnecessary. Don't forget any object needs space and a DataRow is still an object.

Further a List<clsLineaTicket>brings you Object access instead of DataRow access. This is more readable and better for refactorings. So you could easily rename a Property via refactoring. But how to rename a column in your DataTable? You access row["ColumnName"] sometimes? Then you are lost because magic string can't be refactored. Let me show small example for better readablity of List<T>:

Think you are in the event for a double click and you would to show the price of your ticket:

//This event is just a dummy and doesn't exists this way
private void grid_click(object sender, EventArgs e)
{
   //DataTable access
   var row = gridview.GetFocusedRow() as DataRowView;
   MessageBox.Show(Convert.ToString(row["Price"]);

   //List access
   var lineaTicket = gridView.GetFocusedRow() as LineaTicket; //You directly see it's a ticket here
   MessageBox.Show(lineaTicket.Price); //You don't need conversion
}

Another goodie is the possibility of Lambda and Linq. You need a SubList with alle Tickets which got a price lower 10$?

List<clsLineaTicket> lowPriceTickets = ticketList.FindAll(ticket=>ticket.Price < 10);

If you using a List make sure your FieldNames correspond to Propertynames. If you want to make the Grid editable you also need to implement setter on your Properties.

Hope this helps.