Solved

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

Posted on 2007-03-23
10
468 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Turn Insights Into Action

You’ve already invested in ITSM tools, chat applications, automation utilities, and more. Fortify these solutions with intelligent communications so you can drive business processes forward.

With xMatters, you'll never miss a beat.

 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
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 use the auto adjust feature and what the different options do. When your video is not working right you can choose the auto adjust feature to help choose your settings.

717 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