0

I have a table called T_Score and the column called Team1, it has some stored values and I want these values to be added and displayed on a label.

This is the code which stores the values in the table:

private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
    this.NavigationService.Navigate(new LeaderBoard());

    SqlConnection conne = new SqlConnection(@"Data Source=LAPTOP-S2J1U9SJ\SQLEXPRESS;Initial Catalog=Unit4_IT;Integrated Security=True");

    conne.Open();
    string insertQuery = "insert into T_Score(Team1) " +
         "values(@Team1)";
    SqlCommand com = new SqlCommand(insertQuery, conne);

    com.Parameters.AddWithValue("@Team1", txt_score4_tm1.Text);

    com.ExecuteNonQuery();
    conne.Close();
}

This code stores the value that needs to be added with the previous value.

Twenty
  • 5,234
  • 4
  • 32
  • 67
  • 1
    What is the issue you are facing, what have you tried so far? – Twenty Oct 02 '19 at 09:14
  • @Twenty i dont know how to really approach it but im guessing SUM needs to be used. – Mark Mihailovs Oct 02 '19 at 09:17
  • It would help if we would have the datatypes of the values as well. – Twenty Oct 02 '19 at 09:18
  • 1
    You need to 1) add the values, 2) return data from the database and 3) display it in a label. (1 & 2 could be done in either order). Which bit is causing you difficulty? – Robin Bennett Oct 02 '19 at 09:18
  • @Twenty Its intergers. – Mark Mihailovs Oct 02 '19 at 09:19
  • @RobinBennett whats causing me difficulty is know how to add the int values and then displaying the total. – Mark Mihailovs Oct 02 '19 at 09:20
  • @MarkMihailovs - FYI `add` isn't the correct word in this context `1 + 2 = 3` doesn't mean `one add two equals three` it would be `one plus two equals three` and if you want to say you want to `add` any numbers together you are saying `sum up` or `build a sum` or `sum of` instead - so your last sentence should be `... is know how to sum int values ...` – Rand Random Oct 02 '19 at 09:29

1 Answers1

0

Use the following query select sum(Team1) from T_Score; and instead of cmd.ExecuteNonQuery(); use cmd.ExecuteScalar(); and use the return value of the method ExecuteScalar

https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar

Like this:

private void WriteToLabel()
{    
    using (SqlConnection conne = new SqlConnection(@"Data Source=LAPTOP-S2J1U9SJ\SQLEXPRESS;Initial Catalog=Unit4_IT;Integrated Security=True"))
    {
        conne.Open();
        string selectQuery = "select sum(Team1) from T_Score;";
        using (SqlCommand com = new SqlCommand(selectQuery, conne))
            label1.Content = Convert.ToString(com.ExecuteScalar());
    }
}

The line

label1.Content = Convert.ToString(com.ExecuteScalar());

Will require a Label called label1 for it to work. It tries to write the result of Convert.ToString(com.ExecuteScalar()) into the Content property of said Label.

You can also use a TextBlock and than use the Text Property, so this line:

textBlock1.Text = Convert.ToString(com.ExecuteScalar());

Notice instead of calling conne.Close(); manually, I wrapped the SqlConnection conne into a using Statement, this should always be done with objects that inherit from IDisposable.

You can read about IDisposable and the using statement here:


If you have the values already in a IEnumerable object eg. List<int> than you can just do the following

With a simple loop:

var myValues = new List<int>() { 1, 2, 3, 4, 5, 6 }; //<- list with temporary data
var sumOfValue = 0;
foreach (var myValue in myValues)
     sumOfValue += myValue;

With LINQ:

var myValues = new List<int>() { 1, 2, 3, 4, 5, 6 }; //<- list with temporary data
var sumOfValue = myValues.Sum();

If you don't have an IEnumerable of int but instead a class than your code will look like this

public class MyValue
{
    public int Value { get; set; }
    //other properties
}

var myValues = new List<MyValue>() 
               { 
                   new MyValue() { Value = 1 }, 
                   new MyValue() { Value = 2 }, 
                   new MyValue() { Value = 3 }, 
                   new MyValue() { Value = 4 }, 
                   new MyValue() { Value = 5 }, 
                   new MyValue() { Value = 6 }, 
               }; //<- list with temporary data

With a simple loop:

var sumOfValue = 0;
foreach (var myValue in myValues)
     sumOfValue += myValue.Value;

With LINQ:

var sumOfValue = myValues.Sum(x => x.Value);

In all those cases you will have to write sumOfValue into your Label or TextBlock like this

//Label
label1.Content = sumOfValue.ToString();
//or TextBlock
textBlock1.Text = sumOfValue.ToString();

To pass a value to a different page, all you would need to do is the following.

Search for your page in code behind eg. LeaderBoard. It should look something like this

public partial class LeaderBoard : Page
{
    //stuff...
}

Add a new Property to this class

public partial class LeaderBoard : Page
{
    public int MyProperty { get; set; }
    //stuff...
}

When you initialize the LeaderBoard eg. here

this.NavigationService.Navigate(new LeaderBoard());

Change the initialization to this:

this.NavigationService.Navigate(new LeaderBoard() { MyProperty = 7187, });

7187 is a random number this needs to be filled with what ever you need.

With this you have "transfered" data to LeaderBoard and the new property with its value can be accessed in LeaderBoard eg. there could be a method like this

public void Foo()
{
    textBlock1.Text = Convert.ToString(this.MyProperty);
}

The class would than look like this:

public partial class LeaderBoard : Page
{
    public int MyProperty { get; set; }
    //stuff...

    public void Foo()
    {
        textBlock1.Text = Convert.ToString(this.MyProperty);
    }
}

If you need to change the MyProperty from a different place while the LeaderBoard is open keep the reference you have created.

To keep the reference change this line

this.NavigationService.Navigate(new LeaderBoard() { MyProperty = 7187, });

To this

_leaderBoard = new LeaderBoard() { MyProperty = 7187, };
this.NavigationService.Navigate(_leaderBoard);

And create a Field in the outer scope like this

private LeaderBoard _leaderBoard; //<- needs to be outside the method

private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
    _leaderBoard = new LeaderBoard() { MyProperty = 7187, };
    this.NavigationService.Navigate(_leaderBoard);
}

If Btn_LeaderB_Click gets called multiple times but you only want to create 1 LeaderBoard you can do this:

private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
    if (_leaderBoard == null)
        _leaderBoard = new LeaderBoard() { MyProperty = 7187, };

    this.NavigationService.Navigate(_leaderBoard);
}

With that the _leaderBoard field will only get initialized once. If you want to increase the value MyProperty everytime the Btn_LeaderB_Click method gets called you can further extend it to this:

private void Btn_LeaderB_Click(object sender, RoutedEventArgs e)
{
    if (_leaderBoard == null)
        _leaderBoard = new LeaderBoard() { MyProperty = 7187, };
    else
        _leaderBoard.MyProperty += int.Parse(txt_score4_tm1.Text);

    this.NavigationService.Navigate(_leaderBoard);
}
Rand Random
  • 7,300
  • 10
  • 40
  • 88
  • Why is Text giving me an error and insertQuery or am i suppose change that – Mark Mihailovs Oct 02 '19 at 09:49
  • is insertquery suppose to be selectquery – Mark Mihailovs Oct 02 '19 at 09:56
  • it almost works it just doesnt plus the values in the column. – Mark Mihailovs Oct 02 '19 at 10:21
  • @MarkMihailovs - edited my answer to clarify `label1.Text` and fixed the copy & paste error with `insertQuery`. – Rand Random Oct 02 '19 at 10:45
  • @MarkMihailovs - about your problem that my code doesn't produce a sum, this can't be the case since `sum(Team1)` in the `SQL` query, will sum all values in the `Team1` column. Make sure the correct values are in the database. Eg. use SQL Server Management Studio (https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms) to connect to your database and have a look what values are in your table `T_Score` – Rand Random Oct 02 '19 at 10:49
  • I just used a textbloxk that fixed that issue however it still doesnt return the correct sum i will check again. – Mark Mihailovs Oct 02 '19 at 10:57
  • @MarkMihailovs - if you need further assistance you will have to provide more information, like what data is in the table? what sum does the current code produce? what is your expected result? - good luck – Rand Random Oct 02 '19 at 11:57
  • i was thinking maybe this could be easier done without the database and use classes instead for example, have a class where it stores the text box values and then uses thos numbers to just simply add them and display them - dont know if that makes any sense. – Mark Mihailovs Oct 02 '19 at 12:17
  • I might just be over complicating it by using a database – Mark Mihailovs Oct 02 '19 at 12:18
  • @MarkMihailovs - Can't really give an answer to this, since I don't know the greater picture. I updated my answer to show you how to build a sum if you have the values stored in a list. – Rand Random Oct 02 '19 at 12:53
  • my brain cells are melting. Is the new updated asnwer without a database because all im trying to do is store an int and then use it on a different page to create a total. – Mark Mihailovs Oct 02 '19 at 13:07
  • i need to access the stored int on a different page basically. – Mark Mihailovs Oct 02 '19 at 13:17
  • @MarkMihailovs - The new updated answer does not require a database, BUT the main difference is how it gets stored. If you store it in the database it will be "permamently" the new answer is only stored in memory. I don't know your requirement if the value needs to be stored beyond the app life cycle, so if you re-open the app if the value should still be available or gone. If it needs to be available you will need to write the value into a storage eg. DataBase. – Rand Random Oct 02 '19 at 13:20
  • It does not need to be available it would be better if its gone. – Mark Mihailovs Oct 02 '19 at 13:22
  • what i tried is this ` int Score4; Score4 = int.Parse(txt_score4_tm1.Text);` but obviously this dosent allow me to use the value on a different page. – Mark Mihailovs Oct 02 '19 at 13:24
  • okay but the value has to be able to change on button click this is why i have the textbox where to enter the value and then store it when button is clicked. However ill try the new updated answer. – Mark Mihailovs Oct 02 '19 at 13:32
  • @MarkMihailovs - updated once more and the last time for today :) – Rand Random Oct 02 '19 at 13:42
  • `MyProperty = int.Parse(txt_score4_tm1.Text)` would this not technically store the enterd value and then show it. – Mark Mihailovs Oct 02 '19 at 13:42
  • It wont show the value by itself the property `Score` needs to be written into the User Interface eg. TextBlock / Label either manually by somewhere calling `textBlock1.Text = Score.ToString();` or by using a `Binding`. – Rand Random Oct 02 '19 at 13:45