Displaying a datasource field with a label

  • Thread starter Thread starter James R. Davis
  • Start date Start date
J

James R. Davis

I am an absolute beginner and finding myself confused at every step that I
take in the learning process. It will get better.

Anyway, I have a SqlDataSource control on a form and at page load time I
want to display the contents of a field from the record set using a label
control.

I cannot for th elife of me figure out how to reference that field.

The datasource select command simply reads the count(*) of records in the
table via:

SELECT Count(*) As RcdCnt

What I want to do is simply assign that value to Label1.Text but lack of
familiarity with ASP.NET has stopped me cold. I expected to be able to say
something like:

Label1.Text = SqlDataSource1("RcdCnt")

Nope.

I know that there are all levels of knowledge and experience on this news
feed and sincerly hope that a rank beginner's question like this is welcome.
 
What I want to do is simply assign that value to Label1.Text but lack of
familiarity with ASP.NET has stopped me cold. I expected to be able to say
something like:

Label1.Text = SqlDataSource1("RcdCnt")

Hi,

try this way

using (SqlConnection conn = new
SqlConnection(connectionString))
{
conn.Open();

string query = "select COUNT(*) from TABLE_NAME";

SqlDataAdapter da = new SqlDataAdapter(query, conn);

DataTable dt = new DataTable();

da.Fill(dt);

Label1.Text = dt.Rows[0].ToString();
}

I hope that will helps You.

BTW, check this site: http://asp.net/learn/
For me, it is great site for the peoples who starts learning asp.net.
 
Howdy,

Many ways of doing the task at hand, one possible:

string connectionString = "server=serv;database=db;uid=userId;pwd=passw";
int count = 0;

using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(
"SELECT Count(*) As RcdCnt FROM whatever", connection);
count = (int) command.ExecuteScalar();
}

label1.Text = count.ToString();

Hope it helps
 
Once again, Miloz, thank you!

I used the ExecuteScalar method without any trouble at all. In fact, that
was the last piece of the puzzel for my current page. Now off to the next
one!

It's the bits and pieces of practical, everyday, useful information that
aggregates into a 'tool bag' full of capabilities and you have added some
fine ones to mine.

Jim
 
Back
Top