Title: Programmatically add new rows to an unbound DataGridView control in C#
Before writing code, you need to prepare the DataGridView control. Add the control to the form and select it. Click its Smart Tag and then click the Edit Columns link.
Add the columns that you need and set their HeaderText values.
To format the values in a column, click the column's DefaultCellStyle property and then click the ellipsis to the right. Use the CellStyle Builder to set such properties as the column's colors, format, alignment, and wrapping.
Now when you click the program's Add button, the following code adds the new row to the DataGridView.
private void btnAdd_Click(object sender, EventArgs e)
{
// Create the new row.
decimal price_each = decimal.Parse(txtPriceEach.Text);
decimal quantity = decimal.Parse(txtQuantity.Text);
decimal total = price_each * quantity;
dgvValues.Rows.Add(txtItem.Text, price_each, quantity, total);
// Get ready for the next entry.
txtItem.Clear();
txtPriceEach.Clear();
txtQuantity.Clear();
txtItem.Focus();
}
The code first gets the Price Each and Quantity values you entered and uses them to calculate total cost. It then uses the DataGridView's Rows.Add method to create the new row, passing in the row's values.
It is important that this call passes decimal values for Price Each rather than the string value stored in the TextBox. The Price Each column's cell style displays the value formatted as currency, but that only works if the value is numeric, not a string.
The code finishes by clearing the TextBoxes and setting focus to the Item TextBox so the user can easily enter the next row's values.
Download the example to experiment with it and to see additional details.
|