1. Computing

C# Programming Tutorial - Programming Advanced Winforms in C#


5 of 10

How To Use a DataGridView
The Sample DataGridView and other controls

A DataGridView is both the most complex and the most useful component provided for free with C#. It works with both data sources (i.e. data from a database) and without (ie data that you add programmatically). For the rest of this tutorial I'll show using it without Data Sources, For simpler display needs you may find a plain ListView more suitable.

What Can a DataGridView do?

If you've used an older DataGrid control then this is just one of those on steroids: it gives you more built in column types, can work with internal as well as external data, more customization of display (and events) and gives more control over cell handling with freezing rows and columns.

When you're designing forms with grid data, it's most usual to specify different column types. You might have checkboxes in one column, readonly or editable text in another, and of courses numbers. These column types are also usually aligned diferently with numbers generally right aligned so the decimal points line up. At the column level you can choose from Button, checkbox, ComboBox,Image, TextBox and Links. if those aren't enough you can defibe your own custom types.

The easiest way to add columns is by designing in the IDE. As we've seen before this just writes code for you and when you've done it a few times you may prefer to add the code yourself. Once you've done this a few times it provides you with insights into how to do it programmatically.

Let's start by adding some columns, Drop a DataGridView on the form and click the little arrow in the top right hand corner. Then click Add Column. Do this three times. It will pop up an Add Column dialog where you set the name of the column, the text to display at the column top and lets you choose its type. The first column is YourName and and it's the default TextBox (dataGridViewTextBoxColumn). Set the Header Text to yourname as well. Make the second column Age and use a ComboBox. The third column is Allowed and is a CheckBox Column.

After adding all three you should see a row of three columns with a combo in the middle one (Age) and a checkbox in the Allowed column. If you click the DataGridView then in the properties inspector you should locate columns and click (collection). This pops up a dialog where you can set properties for each column such as individual cell colors, tooltip text, width, minimum width etc. If you compile and run you'll notice you can change column widths and run-time. In the property inspector for the main DataGridView you can set AllowUser to resizeColumns to false to prevent that.

On the next page: Adding rows to the DataGridView
  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. How To Use a DataGridView

©2014 About.com. All rights reserved.