How to display the total rows of a table in a label

3

I do not know how to pull the total rows of a table, code:

public string Eventos { get; set; }

SqlCommand comando = new SqlCommand("SELECT count(*) FROM Active", conn);
SqlDataReader leitor = comando.ExecuteReader();
while (leitor.Read()) {
  //Aqui fica o problema pois não sei como faço para pegar o resultado total das linhas
  Eventos = leitor["Nome"].ToString(); 
  label19.Text = Eventos;
}
    
asked by anonymous 26.09.2017 / 18:08

2 answers

5

It is possible to do by SQL, through a count , example:

SELECT COUNT(campo_tabela) AS total FROM tabela

The only thing that will return is total records, more information see MySQL .

To show the values in a label you will need something similar to this, eg:

//string com o comando a ser executado 
string sql = "SELECT COUNT(campo_tabela) AS total FROM tabela"; 

//instância do comando recebendo o comando e a conexão 
SqlCeCommand cmd = new SqlCeCommand(sql, conn); 

//abro conexão 
conn.Open(); 

//instância do leitor 
SqlCeDataReader leitor = cmd.ExecuteReader(); 

//passo os valores para o textbox cliente que será retornado 
txtNome.Text = leitor["total"].ToString();  

//fecha conexão 
conn.Close(); 

To see the more detailed information, visit Microsoft .

EDIT1:

I tried to correct your code to help you, I think you just need to change the value to total in the read and in the query add AS total , while can be removed is used for when there are more records. >

Code:

public string Eventos { get; set; }

SqlCommand comando = new SqlCommand("SELECT count(*) AS total FROM Active", conn);
SqlDataReader leitor = comando.ExecuteReader();

Eventos = leitor["total"].ToString(); 
label19.Text = Eventos;
    
26.09.2017 / 18:14
0

A simple way is to use the ExecuteScalar to get the value of Count(*)

var comando = new SqlCommand("SELECT count(*) FROM Active", conn);

label19.Text = comando.ExecuteScalar().ToString();
    
31.10.2017 / 02:12