C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: You can use the DataSource property to hook your DataGridView up to a database or an object collection.
DataSource: The code sets the DataSource property to the results of another function, GetSearchResults.
DataSourceGetSearchResults: This method performs a custom search. This is custom code that will query a database for results.
Then: It fills a new DataTable. We can use an SqlDataAdapter to fill this DataTable object. The results appear in your DataGridView.
DataTableExample that sets DataSource: C#
/// <summary>
/// Used to set up the data table when the user types a query.
/// </summary>
void BuildDataGrid()
{
dataGridView1.DataSource = GetSearchResults(queryStr);
}
/// <summary>
/// Connect to the database.
/// And then use an adapter to fill a DataTable.
/// </summary>
DataTable GetSearchResults(string queryStr)
{
//
// Make a new DataTable.
//
DataTable table = new DataTable();
//
// You will want to declare a new DataAdapter,
// and then call its fill method on the DataTable.
//
return table;
}
So: Simply create a new List or array of objects, and set the DataSource to this.
ListExample that uses object collection: C#
/// <summary>
/// The test class for our example.
/// </summary>
class TestObject
{
public int OneValue { get; set; }
public int TwoValue { get; set; }
}
void M()
{
TestObject test1 = new TestObject()
{
OneValue = 2,
TwoValue = 3
};
List<TestObject> list = new List<TestObject>();
list.Add(test1);
list.Add(test2); // Not shown in code
dataGridView1.DataSource = list;
}
And: These aren't useful for many kinds of applications. Disable row headers by setting RowHeadersVisible to false.
Tip: This will provide the appearance in the screenshots, which is more streamlined.
Tip: Use StandardTab in the designer to make the tab key move out of the DataGridView and to the next control.
Rows: On the rows collection, there is a method called Add. But it is usually better to modify the DataSource.
Note: The code modifies the new row. Add will give us the index of the new row, so we can modify that row in-place.
ValueType: Every cell has a ValueType. If you want to specify a DateTime column, you can change it by assigning it to a type, using typeof.
DateTimeTypeof, nameofExample that adds rows: C#
/// <summary>
/// Shows example usage of Add method on Rows.
/// </summary>
void M()
{
//
// n is the new index. The cells must also be accessed by an index.
// In this example, there are four cells in each row.
//
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = title;
dataGridView1.Rows[n].Cells[1].Value = dateTimeNow;
//
// The second cell is a date cell, use typeof(DateTime).
//
dataGridView1.Rows[n].Cells[1].ValueType = typeof(DateTime);
dataGridView1.Rows[n].Cells[2].Value = wordCount;
}
But: They do not actually contain the data, just the rules for rendering it to the screen.
DataGridView ColumnsHere: We only take the Y coordinate of the current cell. The current cell is also the selected cell, which usually has a blue highlight.
Example that gets current cell: C#
/// <summary>
/// Shows example usage of how to get the current cell.
/// </summary>
void M()
{
//
// Go from Y coordinate to a selected cell's value.
// DateTime is just for this example, and the Cells[1] part just
// takes the second cell for this example.
//
int yCoord = dataGridView1.CurrentCellAddress.Y;
// You can get X if you need it.
DateTime thisDate = (DateTime)dataGridView1.Rows[yCoord].Cells[1].Value;
}
Tip: When RowIndex is -1, it indicates that the column headers were double-clicked and not a regular cell.
Example that handles double-clicking: C#
void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
//
// Do something on double click, except when on the header.
//
if (e.RowIndex == -1)
{
return;
}
ProceedOpen();
}
CurrentCellAddress: We can check for CurrentCellAddress to figure out what was selected and where the selection moved.
SelectionChanged: This is triggered whenever the selection changes in the DataGridView. You will want to change the display when the selection is moved.
RowCount: When RowCount is zero, then nothing is selected, and our user probably can't proceed in the window.
Example that uses SelectionChanged: C#
void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
//
// When our selection changes, call the function SetupButtons
// to make sure "openButton" is always in a valid state.
//
SetupButtons();
}
/// <summary>
/// Custom method that sets the Enabled property of a button.
/// </summary>
void SetupButtons()
{
//
// Disable openButton when there are no items shown.
//
openButton.Enabled = (dataGridView1.RowCount > 0);
}
First: Your program should have a DataGridView control. You need to add columns and rows to this control somehow.
Next: In Visual Studio, right-click on the DataGridView and select Properties. Then locate the MultiSelect property and change it to False.
Tip: In the screenshot, only one cell is selected because MultiSelect was set to False.
Thus: MultiSelect is a useful property on the DataGridView control. Most programs I have built have it set to False.
And: This is because the programs do not mutate multiple cells at once. The programs are fairly simple.
Tip: Just allow one column to fill up the remainder. You will need to do a bit of manual tweaking.
Example that improves Vista appearance: C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.ColumnHeadersBorderStyle = ProperColumnHeadersBorderStyle;
}
/// <summary>
/// Remove the column header border in the Aero theme in Vista,
/// but keep it for other themes such as standard and classic.
/// </summary>
static DataGridViewHeaderBorderStyle ProperColumnHeadersBorderStyle
{
get
{
return (SystemFonts.MessageBoxFont.Name == "Segoe UI") ?
DataGridViewHeaderBorderStyle.None :
DataGridViewHeaderBorderStyle.Raised;
}
}
}
SortGlyphDirection: You can use this to draw that glyph array image. Remember to remove the glyph arrow in ColumnHeaderMouseClick.
BackgroundColor: Setting this to "Window" often looks best. Looks professional when you adjust this.
SelectionMode: The FullRowSelect enum value looks the best when you are displaying simple result rows.
ColumnHeaderMouseClick: This event is used to capture when a header is clicked. Can be used with ColumnIndex.
ColumnIndex: Sometimes you may need to modify the direction of the sort glyph. You can check e.ColumnIndex on the event parameter.