2012-04-26 2 views
0

Я создаю простую сетку на странице. Данные взяты из процедуры sql. Вот как это выглядит сейчас:Gridview - итоговая и процентная колонка

enter image description here

Мой первый вопрос заключается в том, чтобы вычислить процент для «%» столбцов. Формула довольно проста: Например, в выбранной ячейке она должна быть 15612/238171 * 100%

Я расчет резюме каждой строки следующим образом:

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:Label ID="sprawy" runat="server" Text='<%#Sprawy(Eval("sprawy"),1) %>' /> 
    </ItemTemplate> 
    <FooterTemplate> 
     <asp:Label ID="sumaSpraw" runat="server" Text='<%#GetSumaSpraw(1) %>' /> 
    </FooterTemplate> 
</asp:TemplateField> 

Это мой код для столбца в GridView

И это код функции:

public Int32[] SumaSpraw = new Int32[4]; 

    public Int32 Sprawy(object arg1, int i) 
    { 
     var ilosc = arg1 != DBNull.Value ? Convert.ToInt32(arg1) : 0; 
     SumaSpraw[i - 1] += ilosc; 
     return ilosc; 
    } 

    public Int32 GetSumaSpraw(int i) 
    { 
     return SumaSpraw[i - 1]; 
    } 

Я хотел бы знать, как вычислить значение «%» ячеек на основе резюме из одной строки и значение ячейки.

Мой второй вопрос: Можно ли изменить вид на виде сетки для отображения данных в группе, как так:

enter image description here

ответ

0

мне удалось сделать первую часть, добавляя 2 обработчиков событий gridview, onRowDataBound и onDataBound.

Это мой код для этого методы:

protected void GridViewOnRowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     int i=0; 
     if (sender == GridView1) 
      i = 0; 
     else if (sender == GridView2) 
      i = 1; 


     if (e.Row.RowType == DataControlRowType.DataRow) 
     { 
      SumaSpraw[i] += Convert.ToInt32(((Label)e.Row.FindControl("sprawy")).Text); 
      SumaAdresow[i] += Convert.ToInt32(((Label)e.Row.FindControl("adresy")).Text); 
      SumaInPost[i] += Convert.ToInt32(((Label)e.Row.FindControl("inpost")).Text); 
      SumaPoczta[i] += Convert.ToInt32(((Label)e.Row.FindControl("poczta")).Text); 
     } 
     if (e.Row.RowType == DataControlRowType.Footer) 
     { 
      ((Label)e.Row.FindControl("sumaSpraw")).Text = SumaSpraw[i].ToString("N0"); 
      ((Label)e.Row.FindControl("sumaAdresow")).Text = SumaAdresow[i].ToString("N0"); 
      ((Label)e.Row.FindControl("sumaInPost")).Text = SumaInPost[i].ToString("N0"); 
      ((Label)e.Row.FindControl("sumaPoczta")).Text = SumaPoczta[i].ToString("N0"); 
     } 
    } 

    protected void GridViewOnDataBound(object sender, EventArgs e) 
    { 
     int i = 0; 
     if (sender == GridView1) 
      i = 0; 
     else if (sender == GridView2) 
      i = 1; 

     decimal percent = 0M; 

     foreach (GridViewRow row in ((GridView)sender).Rows) 
     { 
      percent = (Convert.ToInt32(((Label)row.FindControl("adresy")).Text)/SumaAdresow[i]) * 100; 
      ((Label)row.FindControl("procentAdresow")).Text = FormatPercent(Math.Round(percent, 2)); 

      percent = (Convert.ToInt32(((Label)row.FindControl("inpost")).Text)/SumaInPost[i]) * 100; 
      ((Label)row.FindControl("procentInPost")).Text = FormatPercent(Math.Round(percent, 2)); 

      percent = (Convert.ToInt32(((Label)row.FindControl("poczta")).Text)/SumaPoczta[i]) * 100; 
      ((Label)row.FindControl("procentPoczta")).Text = FormatPercent(Math.Round(percent, 2)); 
     } 
    } 

    protected string FormatPercent(decimal percent) 
    { 
     if (percent == decimal.Truncate(percent)) 
     { 
      return percent.ToString("N0") + "%"; 
     } 
     else if (percent * 10 == decimal.Truncate(percent * 10)) 
     { 
      return percent.ToString("N1") + "%"; 
     } 
     else if (percent*100 == decimal.Truncate(percent*100)) 
     { 
      return percent.ToString("N2") + "%"; 
     } 
     else 
      return percent.ToString("N0") + "%"; 
    } 

Третий метод используется для форматирования вывода.

Но все же мне интересно узнать о второй части - как объединить только 2 ячейки из 2 строк (как на моем втором экране).


Я проделал стилизацию. Может быть, этот код не выглядит настолько удивительным, но это работает :)

public static void GridViewRowMerger(GridView gridView, int collIndex) 
    { 
     for (int rowIndex = gridView.Rows.Count - 2; rowIndex >= 0; rowIndex--) 
     { 
      GridViewRow currentRow = gridView.Rows[rowIndex]; 
      GridViewRow previousRow = gridView.Rows[rowIndex + 1]; 

      if (currentRow.Cells[collIndex].Text != previousRow.Cells[collIndex].Text) continue; 
      if (previousRow.Cells[collIndex].RowSpan < 2) 
      { 
       currentRow.Cells[collIndex].RowSpan = 2; 
      } 
      else 
       currentRow.Cells[collIndex].RowSpan = previousRow.Cells[collIndex].RowSpan + 1; 
      previousRow.Cells[collIndex].Visible = false; 
     } 
    } 

    public static void GridViewRefreshStyle(GridView gridView, int collIndex) 
    { 
     int rows = 0; 
     for (int rowIndex = 0; rowIndex < gridView.Rows.Count; rowIndex++) 
     { 
      if (gridView.Rows[rowIndex].Cells[collIndex].RowSpan > 1) 
      { 
       for (int i = 0; i < gridView.Rows[rowIndex].Cells[collIndex].RowSpan; i++) 
       { 
        gridView.Rows[rowIndex + i].CssClass = rows%2 == 0 
                   ? gridView.RowStyle.CssClass 
                   : gridView.AlternatingRowStyle.CssClass; 
       } 
       rowIndex += gridView.Rows[rowIndex].Cells[collIndex].RowSpan - 1; 
      } 
      else 
      { 
       gridView.Rows[rowIndex].CssClass = rows%2 == 0 
                 ? gridView.RowStyle.CssClass 
                 : gridView.AlternatingRowStyle.CssClass; 
      } 
      rows++; 
     } 
    } 

Таким образом, после связывания данных делать GridView я просто называю эти 2 метода следующим образом:

GridView2.DataSource = dSet.Tables[1]; 
GridView2.DataBind(); 
GridViewRowMerger(GridView2, 0); 
GridViewRefreshStyle(GridView2, 0); 
Смежные вопросы