hello
i am new in asp.net and in sql
i want to fetch all different data of same id no and this data make addition to each other
how it possible

such as

invoice_no dabit
111 50
111 100
111 20

according to above sql query select * from table name where invoice_no=111

then it fetch all the all in {dr}
i want that my dabit data make addition in particuler variable
string ss= 50+100+20=170
what code i used in c#
plz give me an example..so that i can impliment it in my project......
plz help me......

Dani AI

Generated

As suggested, the cleanest and most efficient approach is to have the database produce the total. That reduces network traffic and avoids iterating rows in your app. If you need to sum in C# (for custom rules or because rows are already loaded), use a numeric type designed for money, handle nulls, and use parameterized commands to avoid SQL injection.

For Entity Framework / LINQ to Entities (safe, concise; returns zero when nothing matches):

using (var ctx = new MyDbContext())
{
    decimal total = ctx.Records
        .Where(r => r.InvoiceNo == invoiceId)
        .Select(r => (decimal?) r.Dabit)
        .Sum() ?? 0m;
}

For ADO.NET with a forward-only reader (small example showing null handling and proper parameter use):

decimal total = 0m;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT Dabit FROM YourTable WHERE InvoiceNo = @id";
    cmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int) { Value = invoiceId });

    using (var rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            if (!rdr.IsDBNull(0))
                total += rdr.GetDecimal(0);
        }
    }
}

Notes and cautions: use decimal for currency, not float/double. If rows might be absent, use nullable handling (see EF example). Avoid AddWithValue for production code; prefer constructing SqlParameter with an explicit SqlDbType. If you need totals per invoice (multiple ids), group at the DB or use LINQ GroupBy rather than summing each id in a loop. For quick client-side sums on a DataTable, DataTable.Compute or LINQ to DataSet are alternatives. — replace names/types with your real table and column names and check for DBNull when converting.

Recommended Answers

All 2 Replies

I could give you query, you find out asp.net syntax to connect it to database and fetch the total column value

select invoice_no, sum(dabit) total from table name where invoice_no=111
group by invoice_no

thanks dear for helping me............

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.