[英]Getting sum in the gridview data without database
我有一個網格視圖 ,用戶只會向其中添加數據。 但是數據沒有保存到數據庫中。
我要發生的是能夠計算並顯示所有數據量的總和。
我想將總和輸入文本框。 所以,我所做的是
代碼如下:
void gettotal()
{
foreach (GridViewRow row in GridView1.Rows)
{
float GTotal = 0f;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string Amount = GridView1.Rows[row.RowIndex].Cells[4].Text;
GTotal += Convert.ToSingle(Amount);
}
txtSubTotal.Text = GTotal.ToString();
}
}
protected void AddProduct_Click(object sender, EventArgs e)
{
GetPO();
gettotal();
AddNewRecordRowToGrid();
}
每當單擊“ Button Add Product
,它將添加到gridview中。
我嘗試了代碼,並收到錯誤消息
輸入的字符串格式不正確。
第375行:GTotal + = Convert.ToSingle(Amount);
編輯#1
另外:我想獲得有關單擊btn add產品時的金額。 這對我尋找金額的價值有用嗎?
所以我將代碼更改為
string Amount = GridView1.Rows[row.RowIndex].Cells[4].Text;
//string Amount = GridView1.Rows[row.RowIndex].Cells[4].Text;
GTotal += string.IsNullOrEmpty(Amount) ? 0 : Convert.ToInt16(Amount);`
還是說NULL
我認為,如果Cell值為null / empty
,則會引發異常輸入字符串的格式不正確。
您必須通過檢查條件來避免此問題。
嘗試這個:
string Amount = GridView1.Rows[row.RowIndex].Cells[4].Text;
GTotal += string.IsNullOrEmpty(Amount) ? 0 : Convert.ToInt16(Amount);
如果您希望使用任何非數字輸入將其默認設置為0:
int i;
string Amount = GridView1.Rows[row.RowIndex].Cells[4].Text;
if (!int.TryParse(Amount, out i)) i = 0;
GTotal += i;
編輯#1
您需要確保“ Rows and cells
可用,並且其不為null /空。
在這里,您可能需要檢查其他條件。 根據您在Grid中的數據可用性。
if(GridView1.Rows[row.RowIndex] != null && GridView1.Rows[row.RowIndex].Cells[4] != null)
{
// Put the two lines of code here.
}
以上代碼未經測試。 相應地修改if condition
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.