How to display total rows of a table in a label

Asked

Viewed 1,003 times

3

I don’t know how to pull the total lines 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;
}

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 the total records, more information see Mysql.

To show values in a label something similar to this, example:

//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(); 

For more detailed information visit Microsoft.

EDIT1:

I tried to fix your code to help you, I think just change the value to total in reading and adding query AS total, the 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;
  • How can I display the total of lines on the label?

  • see for example: https://code.msdn.microsoft.com/windowsapps/Realizar-select-e-exibir-8d90084c

  • I edited the post with the new code

  • I already edited the answer should need something like the one described in the code

0

A simple way is to use the method Executescalar to obtain the value of Count(*)

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

label19.Text = comando.ExecuteScalar().ToString();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.