Hi makumbisulaiman58,
You need to run loop through all the Data Row cells as well as the Header Row cells and checks whether they are emoty or not.
After getting count of all empty cells you need to subract it from all cells, and you will get count of all filled cells.
Refer below code.
HTML
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText=""/>
<asp:BoundField DataField="Country" HeaderText="Country"/>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblCount" runat="server"></asp:Label>
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add("John Hammond", "United States");
dt.Rows.Add("", "India");
dt.Rows.Add("Suzanne Mathews", "");
dt.Rows.Add("Robert Schidner", "Russia");
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
int emptyCells = 0;
//Checks Data Row cells.
foreach (GridViewRow row in gvCustomers.Rows)
{
for (int i = 0; i < gvCustomers.Columns.Count; i++)
{
if (row.Cells[i].Text == " ")
{
emptyCells += 1;
}
}
}
//Checks Header Row cells.
foreach (TableCell cell in gvCustomers.HeaderRow.Cells)
{
if (cell.Text == " ")
{
emptyCells += 1;
}
}
//Substracting All cells with Empty cells.
int filledCells = (gvCustomers.Rows.Count * gvCustomers.Columns.Count + gvCustomers.Columns.Count) - emptyCells;
lblCount.Text = "Empty Cells:" + emptyCells + "<br/> Filled Cells: " + filledCells;
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Name"), New DataColumn("Country")})
dt.Rows.Add("John Hammond", "United States")
dt.Rows.Add("", "India")
dt.Rows.Add("Suzanne Mathews", "")
dt.Rows.Add("Robert Schidner", "Russia")
gvCustomers.DataSource = dt
gvCustomers.DataBind()
Dim emptyCells As Integer = 0
'Checks Data Row cells.
For Each row As GridViewRow In gvCustomers.Rows
For i As Integer = 0 To gvCustomers.Columns.Count - 1
If row.Cells(i).Text = " " Then
emptyCells += 1
End If
Next
Next
'Checks Header Row cells.
For Each cell As TableCell In gvCustomers.HeaderRow.Cells
If cell.Text = " " Then
emptyCells += 1
End If
Next
'Substracting All cells with Empty cells.
Dim filledCells As Integer = (gvCustomers.Rows.Count * gvCustomers.Columns.Count + gvCustomers.Columns.Count) - emptyCells
lblCount.Text = "Empty Cells:" & emptyCells & "<br/> Filled Cells: " & filledCells
End If
End Sub
Screenshot