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. Set each column's HeaderText.

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.

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 entered by the user. It uses them to calculate total cost.

The code 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 the Price Each rather than the string value 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.