Olá pessoal,
Hj o post é sobre como criar um campo TOTAL no rodapé do Datagrid.
Novamente o exemplo que vou dar aqui é apenas uma idéia do que é possivel fazer.
O código ilustra a seguinte imagem(clique na imagem para ampliar)

Bastar seguir alguns passos
1º - Cria sua página e seu datagrid.
2º - Crie o evento ItemCreated como no seguinte exemplo:
private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
Decimal total = 0;
// Cria o Rodapé com TOTAL
if(e.Item.ItemType == ListItemType.Footer)
{
//Se houver itens a serem renderizados no Datagrid cria o rodapé com TOTAL
if( ViewState["myDataSet"] != null )
{
DataSet ds =
new DataSet();
ds = ( DataSet ) ViewState["myDataSet"];
if( ds != null )
{
// ATENÇÃO: Configurar firstCell com o indice da primeira celula visivel do Datagrid
int firstCell = 0;
// FIM ATENÇÃO
// Cria o Objeto LABEL que vai mostrar o TOTAL
System.Web.UI.WebControls.Label lblTotal = new System.Web.UI.WebControls.Label();
//Formata Label
lblTotal.CssClass="cssSumColor";
lblTotal.Font.Bold = true;
// Calcula TOTAL
for( int i = 0; i < ds.Tables[0].Rows.Count; i++ )
{
string price = ds.Tables[0].Rows[i]["price"].ToString();
total = total + Convert.ToDecimal( price );
}
System.Globalization.NumberFormatInfo nfi =
new System.Globalization.CultureInfo("pt-BR", false).NumberFormat;
nfi.NumberGroupSeparator = ".";
// Adiciona o Texto
lblTotal.Text = "TOTAL " + total.ToString("N",nfi);
// Total de Celulas
int countCells = e.Item.Cells.Count;
// Remove as celulas para o colSpan
for(int i = countCells - 1; i > 1; i--)
{
e.Item.Cells.RemoveAt(i);
}
// Adiciona os controle do Rodapé
// na Primeira celula Visivel
e.Item.Cells[firstCell].Controls.Add(lblTotal);
// Alinha a Esquerda
e.Item.Cells[firstCell].Attributes.Add("align", "Left");
// ColSpan com o Total de Celulas
e.Item.Cells[firstCell].ColumnSpan = countCells;
// Pinta a celula do Rodapé
e.Item.BackColor = Color.FromArgb(219, 219, 219);
}
}
}
}
Posted
29-6-2006 17:37
por
Pedro Antonio Seixas Subutzki