1. Computing
Send to a Friend via Email

C# Programming Tutorial - Programming Advanced Winforms in C#

By

6 of 10

Adding rows to the DataGridView Programmatically
Setting the Event Handler for the Leave event

We're going to add rows to the DataGridView control in code and ex3.cs in the examples file has this code. Starting by adding a TextEdit box, a ComboBox and a button to the form with the DataGridView on it. Set the DataGridView property AllowUserto AddRows to false. I use labels as well and called the combobox cbAges, the button btnAddRow and the TextBox tbName. I've also added a Close Button for the form and double clicked it to generate a btnClose_Click event handler skeleton. Adding the word Close() there makes that work.

By default the Add Row button enabled property is set false on start. We don't want to add any rows to the DataGridView unless there is Text in both the Name TextEdit box and the ComboBox. I created the method CheckAddButton and then generated a Leave event handler for the Name Text edit box by double clicking next to the word Leave in the Properties when it was displaying the events. The Properties box shows this in the picture above. By default the Properties box shows properties but you can see event handlers by clicking the lightning button.

private void CheckAddButton()
{
    btnAddRow.Enabled = (tbName.Text.Length > 0 && cbAges.Text.Length > 0) ;
}

You could use have used the TextChanged event instead, though this will call the CheckAddButton() method for every keypress rather than when teh control is leaved i.e. when another control gains focus. On the Ages Combo I used the TextChanged event but selected the tbName_Leave event handler instead of doubleclicking to create a new event handler.

Not all events are compatible because some events provide extra parameters but if you can see a previously generated handler then yes you can use it. It's mostly a matter of preference, you can have a separate event handler for every control that you are using or share event handlers (as I did) when they have a common event signature, i.e. the parameters are the same.

I renamed the DataGridView component to dGView for brevity and double clicked the AddRow to generate an event handler skeleton. This code below adds a new blank row, obtains that rows index (it's RowCount-1 as it's just been added and RowCount is 0 based) and then accesses that row via its index and sets the values in the cells on that row for the columns YourName and Age.

dGView.Rows.Add() ;
int RowIndex = dGView.RowCount - 1;
DataGridViewRow R= dGView.Rows[RowIndex];
R.Cells["YourName"].Value = tbName.Text;
R.Cells["Age"].Value = cbAges.Text;

On the next page: Container Controls

©2014 About.com. All rights reserved.