Wednesday, May 27, 2009

DataGridView - a simple example

I usually need a simple datagrid that is populated from a callback instead of a database. Here is an example of how to do this.

1. Create two instances
private DataSet dsDataSet = new DataSet;
private DataTable dt;

2. In the constructor of your application initialize the data table
dt = dsDataSet.Tables.Add("Prices");

3. Create a function to create columns

public void setUpDataGridView()
DataColumn dc1 = new DataColumn();
dc1.ReadOnly = false;
dc1.ColumnName = "BidPrice";
dc1.DataType = typeof(string);

DataColumn dc2 = new DataColumn();
dc2.ReadOnly = false;
dc2.ColumnName = "BidQty";
dc2.DataType = typeof(string);

DataColumn dc3 = new DataColumn();
dc3.ReadOnly = false;
dc3.ColumnName = "AskPrice";
dc3.DataType = typeof(string);

DataColumn dc4 = new DataColumn();
dc4.ReadOnly = false;
dc4.ColumnName = "AskQty";
dc4.DataType = typeof(string);

dataGridView1.DataSource = dt;

4. In your callback for the event that gets the data add the rows

DataRow workRow = dt.NewRow();

workRow["BidPrice"] = stringBidPrice;
workRow["BidQty"] = stringBidQty;
workRow["AskPrice"] = stringAskPrice;
workRow["AskQty"] = stringAskQty;


1 comment:

Alex McFerron said...

using the CellClick callback you can get the row and index

int intRowIndex = e.RowIndex;
int intColumnIndex = e.ColumnIndex;