2012-05-10 39 views
0

我有問題,讓我的GridView的特定小區的數據獲得的數據 我做這樣說:無法從我的GridView

double total = 0; 

for (int i = 0; i < GridFactures.Rows.Count; i++) 
    total += Convert.ToDouble(GridFactures.Rows[i].Cells[6].Text.ToString()); 

lblTotalTTC.Text = "Montant total TTC : " + total; 

問題列在我的aspx文件中聲明:

<asp:TemplateField HeaderText="Montant TTC"> 
    <ItemTemplate> 
     <asp:Label ID="lblMontantTTC" runat="server" Text='<%#Eval("MontantTTC") %>'/> 
    </ItemTemplate> 
</asp:TemplateField> 

我敢肯定這總是我想檢查的第六列。 我把休息和GridFactures.Rows[i].Cells[6].Text.ToString()總是包含「」 僅此而已...... 感謝您的幫助

回答

0

如果我沒有誤(和你的標籤是在電池的第一/只控制) -

你必須在索引0索要控制,或通過ID找到它,然後詢問。文本

像這樣:

GridFactures.Rows[i].Cells[6].Controls[0].Text.ToString() 
+0

不幸的是,這是行不通的。我無法實際從gridview中獲取任何數據。 – Slrg

+1

出於測試目的,請嘗試使用GridFactures.Rows [i] .FindControl(「lblMontantTTC」)方法,並查看是否可以找到它。 –

+0

再次感謝,但它不工作...我不明白 – Slrg

0

記住這是一個從零開始的索引,所以[6]是指細胞7

+0

是的,我知道啦!我從0開始計數。 但是,謝謝! – Slrg

+0

赫赫是一個錯誤,經常只是要確保;) – RhysW

0

我知道爲什麼。我自己也遇到了同樣的情況。您需要檢查空的字段,如果是,請先將其轉換爲零。

total += (GridFactures.Rows[i].Cells[6].Text == "")? 0d : Convert.ToDouble(GridFactures.Rows[i].Cells[6].Text.ToString()); 
1

如何使用LINQ代替循環?

double mySum = 
     GridFactures.Rows 
        .Cast<GridViewRows>() 
        .Sum(row => 
       Double.Parse(((Label)row.FindControl("lblMontantTTC")).Text)); 

如果你看到任何值,那麼你實際上電網尚未數據綁定,又或ViewState是對電網禁用。這完全取決於您在頁面生命週期中何時/何時執行此計算。

2

,而不是驗證碼:

for (int i = 0; i < GridFactures.Rows.Count; i++) 
    total += Convert.ToDouble(GridFactures.Rows[i].Cells[6].Text.ToString()); 

試試這個:

for (int i = 0; i < GridFactures.Rows.Count; i++) 
{ 
    Control ctrl = GridFactures.Rows[i].Cells[6].FindControl("lblMontantTTC"); 
    if (ctrl != null) 
    { 
     Label lbl = ctrl as Label; 
     if (lbl != null) 
     { 
      total += Convert.ToDouble(lbl.Text); 
     } 
    } 
}