help plz....hi i wud like to know how to count each row of a datagrid and display the answer in a textbox. thks

Dani AI

Generated

wanted a row count and a column sum. Replies drifted between WinForms and WebForms — asked the right clarifying question, pointed toward the grid control's built‑in row count, and showed a loop for a WinForms grid. Below are concise, practical options for ASP.NET (VB.NET) WebForms plus a few gotchas.

If the grid is bound to a DataTable, use the DataTable for counts and aggregates (fast and unaffected by paging):

Dim dt As DataTable = TryCast(GridView1.DataSource, DataTable)
If dt IsNot Nothing Then
    TextBoxCount.Text = dt.Rows.Count.ToString()
    Dim total As Decimal = If(dt.Rows.Count > 0, Convert.ToDecimal(dt.Compute("SUM(Amount)", String.Empty)), 0D)
    TextBoxSum.Text = total.ToString("F2")
End If

If you must sum the visible rows in a DataGrid/GridView (e.g., after paging or when using template fields), iterate the items and parse the cell or control value safely:

Dim cnt As Integer = DataGrid1.Items.Count
Dim sum As Decimal = 0D

For Each item As DataGridItem In DataGrid1.Items
    Dim txt As String = item.Cells(1).Text  ' or find control inside template
    Dim v As Decimal
    If Decimal.TryParse(txt, v) Then sum += v
Next

TextBoxCount.Text = cnt.ToString()
TextBoxSum.Text = sum.ToString("F2")

Troubleshooting tips: run this after DataBind (or in DataBound/RowDataBound), handle DBNull and formatted text (currency/commas) with TryParse and appropriate NumberStyles, and be aware of paging (server-side counts require the full data source or a SQL aggregate). For WinForms grids, the loop approach works but watch for the editable "new row" if the control allows user additions.

Recommended Answers

All 6 Replies

Count each row or sum up a column?

Use dataGridView1.Rows.Count property.

Count n sum up too.

assuming u want to sum up the values of first column

dim counter as integer = 0
dim sum as integer = 0
while counter < datagridview1.rows.count
sum = sum+datagridview1.items(0,counter).value
counter = counter +1
end while

fgvhgvhgyghvgyhbvhgy

I'm cannot run at the cmd to become a exe.file application


"now how I to do this"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.