gymcode
gymcode

Reputation: 4633

Get GridView Row Count with Condition

I am using VS2005 ASP.NET C# and SQL Server 2005.

I have a GridView on my webpage and a couple of labels.

I am able to allocate the value of the number of rows into a label by the following:

UserFound.Text = GridView1.Rows.Count.ToString();

However, I would like to allocate another value to another label which counts the number of rows when the value inside column Role is equals to "admin".

How can I do it? Examples and sample code will be appreciated.


EDIT:

int admincount=0;
foreach (DataRow oRow in GridView1.Rows)
{
    if (GridView1.Rows["User Role"].ToString().Trim().Contains("Admin"))
    {
        admincount++;
    }
}

AdminFound.Text = admincount.ToString();

I am getting the error:

The best overloaded method match for System.Web.UI.WebContols.GridViewCollection.this[int] has some invalid arguments and

Argument '1': canot convert from 'string' to 'int'

Upvotes: 0

Views: 6535

Answers (2)

gsirianni
gsirianni

Reputation: 1364

You could run sqlCommand.ExecuteScalar() with a select statement like:

select Count(UserRole) where UserRole = 'Admin'  

The value returned you can then use as your label text;

Upvotes: 1

william
william

Reputation: 7704

Well.. I assume u use ADO.Net

Before GridView1.DataBind(), do a for loop to Gridview or the datatable which you are going to bind to Gridview1

int admRows=0;
for(int i=0;i<datatable1.Rows.Count;i++)
{
  if(datatable1.Rows[i]["adminColumn"].ToString().Trim().ToLower().Contains("admin"))
  {
    admRows++;
  }
}
admFound.Text=admRows.ToString();
GridView1.DataSource=datatable1;
GridView1.DataBind();

P.S. datatable1.Rows[i]["adminColumn"] or datatable1.Rows["adminColumn"][i].. i m not sure.. google it

Upvotes: 1

Related Questions