Question

I have a tableadapter (SettlementCurrentTableAdapter) with a relation. parent table is (SettlementCurrent) child table is (Trips).

I need to SUM each row (tripLoadedMiles) in (Trips) and display the total in a label (labelWelcomeSetTotalMiles).

I would like to do this in code and not sql as i use this tableadapter to display other labels.

Can someone help me figure this out. i am new to C# and i use Visual C#.

        this.settlementCurrentTableAdapter.Fill(this.myLeaseDataSet.SettlementCurrent);
        MyLeaseDataSet.SettlementCurrentRow settlementCurrent;
        settlementCurrent = myLeaseDataSet.SettlementCurrent.Last();

        var settlementCurrentID = settlementCurrent.setID;

        this.tripsTableAdapter.FillByTripSetID(this.myLeaseDataSet.Trips, settlementCurrentID);
        MyLeaseDataSet.TripsDataTable settlementTrips;
        settlementTrips = myLeaseDataSet.Trips;
        foreach (DataRow row in myLeaseDataSet.Trips.Rows) 
        {

            NOT SURE ON THE CODE HERE

        }
Was it helpful?

Solution

Your first step is to extract the data you want out of your data adapter. Since I don't have a table model in your question, it is best to look at the table adapter overview on MSDN, and click on the related links and articles to figure out the basic usage of this object. If you were to post your table structure, I could theoretically give you some code for it, but I'm reluctant to do that - you will have to work with this object a lot of it's how you're talking to your database, so it's imperative you learn how it functions.

Your goal in this learning is to figure out how to get all the miles figures out of your table adapter. You usually do this by going over one row at a time, and picking out the values you want to add them to a more C# idiomatic data structure, such as a a List/IEnumerable, or an Array.

After you have the data you need in one of these structures, you can get the sum of everything by using LINQ. Depending on how much you pulled out, it can be as simple as one call (if this is something like an Array of ints):

var totalMiles = tripLoadedMiles.Sum();

Or as elaborate as you might need (if this is a List of a custom object that has both SettlementCurrentId and Miles, both stored as ints):

var totalMiles = tripLoadedMiles.Select(x => x.SettlementCurrentId == someRandomRequiredSettlement).Sum(y => y.Miles);

In the way you're using things, this is how you're looking at totaling it in this situation.

    var total = 0;
    foreach (DataRow row in myLeaseDataSet.Trips.Rows) 
    {

        total += int.Parse(row["tripTotalMiles"].ToString());
    }
    // Use the total
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top