Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleProgrammatically add new rows to an unbound DataGridView control in Visual Basic .NET
DescriptionThis example shows how to programmatically add new rows to an unbound DataGridView control in Visual Basic .NET
KeywordsDataGridView, add rows, Visual Basic .NET, VB.NET, controls
CategoriesControls, VB.NET
 
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 Sub btnAdd_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnAdd.Click
    ' Create the new row.
    Dim price_each As Decimal = _
        Decimal.Parse(txtPriceEach.Text)
    Dim quantity As Decimal = _
        Decimal.Parse(txtQuantity.Text)
    Dim total As Decimal = price_each * quantity
    dgvItems.Rows.Add(txtItem.Text, price_each, quantity, _
        total)

    ' Get ready for the next entry.
    txtItem.Clear()
    txtPriceEach.Clear()
    txtQuantity.Clear()
    txtItem.Focus()
End Sub
 
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.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated