Solved

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

Posted on 2007-03-23
10
464 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
Comment Utility
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_
Comment Utility
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
Comment Utility
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
 
LVL 2

Expert Comment

by:_Eyeball_
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 11

Accepted Solution

by:
Mihai Stancescu earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The goal of the tutorial is to teach the user how to live broadcast using Flash Media Live Encoder and connecting it to YouTube to broadcast. Log into your Youtube account, choose live stream settings, start live stream from Flash Media Live Enc…
The goal of the tutorial is to teach the user how to select the video input device. Make sure you have an input device that in connected and work and recognized by Adobe Flash Media Live Encoder and select it in the “video input” menu.

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now