Tutorial :How do I create a DataGrid in C#?



Question:

I want to add a DataGrid to a Form. When the program executes, the user enters values and I use those values in the problem. I need a similar implementation for a table with two columns and when the user enters values I use them to for calculation in the program.

There is no requirement to save these values to a database, they are just going to be used in the program.

How do I do this in C#?


Solution:1

In a winforms environment, you can bind strongly typed collections as the datasource; Each property of the objects in the collection makes a column (Strictly speaking, I believe it works out the properties for the type that the collection returns, rather than the individual items in it)


Solution:2

If you are writing a WinForms App then you can use a DataTable to store the data and a DataGridView to display it. Simply create the DataTable:

dataTable = new DataTable();  

Create the columns you need programatically:

var columnSpec = new DataColumn();  columSpec.DataType = typeof(decimal);  // If it holds a decimal  columSpec.ColumnName = "Interest Rate";  dataTable.Columns.Add(columnSpec);  

Add the DataGridView to the form using the Designer - but don't and then once the table has been created bind it to the grid using:

dataGridView.DataSource = dataTable;  

You can set the properties on the grid from the designer view.

I have done this in a read-only case where the DataTable is populated from the program and just displayed it. All the user can do is resize, reorder or set the visibility on the columns. To add new rows you'll need to hook into the RowsAdded event


Solution:3

Re-wording Rowland Shaw

You need not have a database to bind to the datagrid. If you have the data filled in a strongly typed or a generic collection you can bind the datagrid to the collection. The datagrid will fill the data from the collection.

It will take the property names as the columns, and the rows will display as per the rows in the collection.

If you want user input, then I think you should consider using a better grid control. The datagrid is not suitable for this purpose. I dont' remember if flexgrid (the ocx one) has been redone for .Net.


Solution:4

You can use a datagridview and build a datatable and add columns through your code and set the datatasource of your datagridview as this datatable and set AllowUserToAddRows in properties window of Dataggridview to true ( true is the default value ).

If you want to make the calculation after a full ro update is made then you can use RowPrePaint event or if you want the calculation to be made after the data in each cell gets updated then you can use the CurrentCellChanged event of the datagridview.

Hope this helps....


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »