Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Query inside a Messagebox

Status
Not open for further replies.

kizzieb

Technical User
Oct 16, 2007
6
GB
Hello

I am trying to get the total of a query to show up inside a message box, an example of the coding is as shown below:

private void btnTotal_Click(object sender, EventArgs e)
{
conn.Open();
cmd.CommandText = "select sum(weight)FROM tbl_Fleet";
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show(cmd.CommandText);
}
}
 
You want the result to show up? (Like the number 10 popping up in a dialog) or are you looking for the query text ("Select sum(weight)from...." to show up?

If it's the first option - you will want to populate a datatable and get the value from that.


In this case they are passing in a DataSet which returns tables. Change your select statement to

select sum(weight) as weight FROM tbl_Fleet

And then use the method shown in the article and you can get your value like this:

string weight = ds.Tables[0].Rows[0]["weight"].ToString();

Keep in mind this is very primitive and if anything were to go wrong you would know about it in a hurry (EXCEPTION!)

 
since the query only returns a single value you an execute scalarquery and cast the result to an integer.
Code:
private void btnTotal_Click(object sender, EventArgs e)
{
   int count = 0;
   using(conn)
   {
      conn.Open();
      cmd.CommandText = "select sum(weight)FROM tbl_Fleet";
      count = (int)cmd.ExecuteScalar();
   }

   MessageBox.Show(count.ToString());
}
the using key word automatically closes/disposes the conn object

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
while [tt]using[/tt] is an absolute essential, what happens when the user clicks the button twice?

is it a good idea to dispose of objects you didn't create?



mr s. <;)

 
Putting the connection into a data access layer is the best idea. Wrap all queries in a try catch finally and dispose of your connection in the finally.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top