Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Display SQL output into textbox

I am having issues trying to display the result of an SQL query into a textbox in my WPF program. My code looks like this:

private void btnCompare_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string commandText = "SELECT ID, FirstName, LastName, Email, City FROM ( SELECT ID, FirstName, LastName, Email, City FROM CompareTable UNION ALL SELECT MainTable.ID, MainTable.FirstName, MainTable.LastName, MainTable.Email, MainTable.City FROM MainTable )  CompareTable GROUP BY ID, FirstName, LastName, Email, City HAVING COUNT(*) = 1";
                SqlConnection conn = new SqlConnection(connectionstring);
                SqlCommand comm = new SqlCommand(commandText, conn);
                conn.Open();
                txtResult.Text = (string)comm.ExecuteScalar();
                conn.Close();
            }catch(Exception d)
            {
                MessageBox.Show(d.ToString());
            }
                
        }

When I run the query in the Azure DB, I get the output I’m looking for.
But the for some reason, the result output is an Int32 variable, this is the error I get:
enter image description here

Can someone explain why the output is not a string?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

ExecuteScalar() returns a single value, which is the first column of the first row if the query returns a table. So it’s trying to "cast" the first ID from an integer to a string and fails. I suspect you want ExecuteReader instead, loop through the results, and build a string somehow.

Or you could fill a DataTable and get the data from the rows and columns of that. There are plenty of examples out there of both methods.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading