Solved

showing count(*) in a C# windows application.

Posted on 2007-03-23
10
465 Views
Last Modified: 2012-06-27
Hello:

I am writing a sample windows application in C# to learn the language, etc.

Essentially, what I want to do is display the number of records in a particular table when the application loads. So, in my form I have two text labels like this:

lbl1_txt.text = "The number of rows in your table is ..."
lbl2_result.text = "36" (this 36 is theoretically the amount of entries in the table).

I have a database that I connected to this application. It gets the connection string and all that has been established. But being a newbie I only know how to display data via grid view and don't know the code to substitute "36" with the result of "SELECT COUNT(*) FROM my_table"

Any help would be much appreciated

Thanks!
0
Comment
Question by:freezegravity
  • 3
  • 3
  • 2
10 Comments
 

Author Comment

by:freezegravity
ID: 18784497
oh and I am using Visual C# 2005 Express Edition (essentially like Visual Studio but only for C# windows application) for Windows Vista. That may be relevant as maybe with earlier versions the procedure was different.

Thanks!

 
0
 
LVL 2

Expert Comment

by:_Eyeball_
ID: 18784525
I'm sorry but I'm afraid I don't get the core of your question...

You already have the "36" and don't know how to set it into the label? (as you did before) lblName.Text = "36";

 Or don't you know how to get the result (e.g. 36)? If the data is already in a datagrid multiplicate the number of rows with the number of colums. datatable.Rows.Count * datatable.Colums.Count. When you do it that way there could be problem by converting the long (36) to a string. do this by erg.ToString();

I hope I did understand your question the right way... Otherwise I'm sorry

best regards
0
 

Author Comment

by:freezegravity
ID: 18784571
36 is just a sample number ...

I know how to get the result in SQL Server Management Studio but how do I display it in the lbl_result.text.

Where would I add your code of "datatable.Rows.Count*"?

Thanks for trying to answer!

0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 2

Expert Comment

by:_Eyeball_
ID: 18784585
OK... where do you do you get the rows? Are you still in the class which inherits from the System.Windows.Forms.Form? In this case you can easily (after you filled the datagridview) write the following code:

this.label1.Text = this.dataGridView1.RowCount.ToString(); // I'm sorry it's a propertie no methode ;)

or:

this.label1.Text = yourResult;

in case it's a long or anything else than a string:

this.label1.Text = yourResult.ToString();

If you do the database questioning in another class it's best you do the setting you would do best by a delegate. You would give a delegate by the constructor to the db class. Would look something like that:

// MainClass
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        private db m_MyDB;

        public Form1()
        {
            InitializeComponent();
            this.m_MyDB = new db(new EventHandler(DoEvent));
        }

        private void DoEvent(object sender, System.EventArgs e)
        {
            // casting
            string result = null;      
            if (sender is string)
                result = (string)sender;

            if (result != null) // Yep, got result
                this.label1.Text = result;
        }
    }
}

//DB
namespace WindowsApplication1
{
    class db
    {
        private System.EventHandler m_EventToThrow;

        public db(System.EventHandler eventToThrow)
        {
            this.m_EventToThrow = eventToThrow;

            string res = String.Empty;
            // Do DB call
            //...
            // get result... res = yourresult;
            m_EventToThrow(res, new EventArgs());
        }        
    }
}

Of course you can call the eventhandler whenever you want... Furthermore you can write your own delegate, but I think this solution is easier. Of course, if the number of rows you get by a methodcall it's much easier... in this case you can do (in your mainclass)

this.label1.Text = db.MethodToGetNumberOfRows();

If you're runnign the db in another thread we have to add some code for invoke...

I hope this would help!

best regards
0
 
LVL 11

Accepted Solution

by:
Mihai Stancescu earned 500 total points
ID: 18863144
You can use a SqlDataReader if the database is MSSQL or an OleDbDataReader if you use an oledb connection.

ex(from MSSQL):

     public int GetTotalItems()
     {
         int res =-1;
        SqlCommand cmd = new SqlCommand("select count(*) from Table", DBConnection);
        DBConnection.Open();
       SqlDataReader rd = cmd.ExecuteReader();
       rd.Read();
       res = rd.GetInt32(0);
       rd.Close();
       DBConnection.Close();
       return res;
     }
Hope this helps.

Regards,
Mishu
0
 
LVL 11

Expert Comment

by:Mihai Stancescu
ID: 18863148
Then you can use this :
lbl2_result.text = GetTotalItems().ToString();
or you can convert it separately:
int i = GetTotalItems();
lbl2_result.text = i.ToString();
0
 

Author Comment

by:freezegravity
ID: 18901030
Mishu007:

Can you explain what your code does? i.e. how it does what it is supposed to?

Thanks.

FG!
0
 
LVL 11

Expert Comment

by:Mihai Stancescu
ID: 18904094
Ok, I' ll try to explain the code.

First the method "GetTotalItems()" witch returns an int value.
There we execute a query to the data base to get the count(*) value instead of your example (36).
Then we use a SqlDataReader to read the value that the query returns, by using (SqlDataReader rd = cmd.ExecuteReader();
       rd.Read();
       res = rd.GetInt32(0);
       rd.Close();
)
After we close the database connection if you don't need it anymore, but you can leave it open...
Then we just call the method as I show in my second post.

Hope this helps and clear things out.

Regards,
Mishu
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C# guarantee sql connection close 6 39
C# Desktop Application 3 30
Problem!!! 8 33
.NET 2008 VB and C# 6 27
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this tutorial viewers will learn how to create a basic motion tween animation in Flash Open a new document in Flash: Draw/import an image: Press CTRL + F8 to convert it into a graphic symbol: Select a frame (how long you want the tween to last): …
The goal of the tutorial is to teach the user what frame rate is, how to control it and what effect it has on the video.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question