Reputation:
I have problems to get the data of a particular cell in my gridview i'm doing it this way :
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;
The column in question is declared in my aspx file :
<asp:TemplateField HeaderText="Montant TTC">
<ItemTemplate>
<asp:Label ID="lblMontantTTC" runat="server" Text='<%#Eval("MontantTTC") %>'/>
</ItemTemplate>
</asp:TemplateField>
i'm sure this is always the sixth column i want to check.
i put a break and GridFactures.Rows[i].Cells[6].Text.ToString()
always contains ""
nothing more ...
thanks for your help
Upvotes: 0
Views: 750
Reputation: 5899
Instead of this code:
for (int i = 0; i < GridFactures.Rows.Count; i++)
total += Convert.ToDouble(GridFactures.Rows[i].Cells[6].Text.ToString());
Try this:
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);
}
}
}
Upvotes: 1
Reputation: 100567
How about use LINQ instead of looping?
double mySum =
GridFactures.Rows
.Cast<GridViewRows>()
.Sum(row =>
Double.Parse(((Label)row.FindControl("lblMontantTTC")).Text));
If you're seeing no values, then your grid actually hasn't been databound yet, or ViewState is disabled on the grid. This all depends on where/when you're performing this calculation in the page lifecycle.
Upvotes: 0
Reputation: 86
I know why. I just ran into the same situation myself. You need to check fields that are empty, if so, convert it to zero first.
total += (GridFactures.Rows[i].Cells[6].Text == "")? 0d : Convert.ToDouble(GridFactures.Rows[i].Cells[6].Text.ToString());
Upvotes: 0
Reputation: 16
If I'm not mistaken (and your label is the first/only control in the cell) -
You need to ask for the control at index 0, or find it by id, then ask for the .Text
Like so:
GridFactures.Rows[i].Cells[6].Controls[0].Text.ToString()
Upvotes: 0