![](/img/trans.png)
[英]How can I properly get my 'Calculate' button to calculate the total price and discount amount in ASP.NET C#?
[英]How can I add and get all my database table values (numbers) and displaying the total amount? C#
我最近在努力解決一個新問題。 我有一個數據庫表,其中包含多個字段(列),其中包含幾行,包含與字段名相關的(money - decimal)值。
例如:
我想要做的是從數據庫中獲取這些值,將它們一起添加並在標簽中顯示總量。
到目前為止,我使用OleDbDataReader來滿足我所有的輸出/存儲價值需求。 雖然我完全不知道如何添加讀取值,因為讀者通常希望讀取預定義的字段名稱。
但是,在我的項目中,用戶可以添加自定義新字段名稱(因此您無法在閱讀器中預先定義字段名稱,因為您不知道用戶將在數據庫中添加哪些自定義字段名稱。這些自定義添加的字段名稱及其值也需要在總量中添加,但..
有誰知道如何解決這個問題?
我嘗試了多種方法,比如將它存儲在一個數組中,定義十進制變量並使用像x = x + (decimal)reader[0]
但這一切都沒有用,所以我想我離開了。
我用於閱讀部分的代碼(和查詢)如下:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from money where [Month]='January'";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//Something I tried
//x[0] = (decimal)reader[0];
//x[1] = (decimal)reader[1];
//And so on...
//Another thing I tried
//list.Add(reader.GetInt32(0));
}
//list.ToArray();
//int sum = list.Sum();
// y = x[0] + x[1] + ...;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
您應該只能聲明一個變量,然后將所有列相加。 如果您不知道閱讀器中的列數,可以使用reader.FieldCount
。
您無需知道列名即可從閱讀器獲取數據。 您可以在開始時通過列索引訪問它,例如reader[0]
,或使用諸如GetDecimal(0)
類的輔助方法。
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from money where [Month]='January'";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
// start the total at 0
int total = 0.0m;
while (reader.Read())
{
// loop through all the fields in the reader
for(int f = 0; f < reader.FieldCount; f++) {
// read as a decimal and add to the total
total += reader.GetDecimal(f);
}
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
希望這可以幫助 -
decimal total = 0M;
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
total+= (decimal) (dr[i] != DBNull.Value ? dr[i] : 0.0);
}
}
這將為每一行添加所有列的值。
Datareader具有稱為字段計數的屬性,可以給出列數..因此您可以使用類似下面的內容
double num=0.0m;
for (int i = 0; i < rdr.FieldCount; i++)
num += rdr[i];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.