How to view / send data (sum column values) from the SQL Server database in C # WinForm textBoxes

advertisements

I'm trying to display the sum up certain columns from my SQL Server database into Winforms textboxes but I'm facing difficulties and I don't know further.

This how my table in the database looks like:

My C# code:

if (combobox1.SelectedText != null)
{
    string CS = (@"Data )

    SqlConnection con = new SqlConnection(CS);

    SqlCommand sqlCmd = new SqlCommand();
    sqlCmd.Connection = con;
    sqlCmd.CommandText = ("[dbo].[spSalesAnalyse]");
    sqlCmd.CommandType = CommandType.StoredProcedure;

    cbAnalyse.SelectedValue.ToString());
    SqlDataReader myReader;

    try
    {
         con.Open();
         SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd);
       // Save the results in the DT. Call the adapter statement and fill it in the DT
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                //Fill textBoxes with data in DT
                textBox1.Text = dt.Rows[0].Field<string>("North");
                textBox2.Text = dt.Rows[1].Field<string>("East");
                textBox3.Text = dt.Rows[2].Field<string>("West");
                ....
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        con.Close();
    }
}
else
    MessageBox.Show("Error");

My expectation:

The Problem: If I debugg till this line adapter.Fill(dt), I do see the records BUT they are not getting to my textBoxes. They are empty when debugg reach textBoxes level

Hope I did express myself well


Looks like you are trying to get one textbox value at a time. You could use the GROUP BY clause in SQL to fetch your data.

SELECT
  Country,
  Region,
  SUM([Sales1]) AS [First Sales],
  SUM([Sales2]) AS [Sec Sales],
  SUM([Sales3]) AS [Third Sales]
FROM
  [dbo].[tblSales]
GROUP BY Country, Region

A single query will return all your results. You can take this results in a DataSet and then set the values of the corresponding textboxes by fetching values from the DataSet.

//Use query string as show above
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);

Now that you have records inside your DataSet, you can fill your textboxes.

DataRow dataRow = dataset.Tables[0].Select("Country = 'Italy' AND Region = 'North'").FirstOrDefault();
if (dataRow != null) {
    textbox1.Text = dataRow["First Sales"].ToString();
}