2013-02-01 30 views
1

我有一个GridView,其中第一列显示一组三个冗余数据。我需要消除这种冗余,以便只显示代码的一个实例。在OnView数据绑定事件中在GridView中格式化数据

这里是GridView的样子:

A1234 | Total Entries     | 1 | 7 |  |     
A1234 | Equipment Entries    | 1 | 7 |  |     
A1234 | Total Repair Time    | 60 | 140 |  |     
B9876 | Total Entries     | 87 | 36 | 14 | 
B9876 | Equipment Entries    | 87 | 36 | 143 | 
B9876 | Total Repair Time    | 2070 | 790 | 370 | 
C3456 | Total Entries     | 1 |  |  |   
C3456 | Equipment Entries    | 1 |  |  |  
C3456 | Total Repair Time    | 190 |  |  | 

我希望它看起来就像是(我似乎无法得到它的格式正确)那么在第一列中的代码A1234,B9876 ,而C3456只显示一次而不显示三次 - 因此存在黑色空间/单元格。

,我有最新的代码基本上是这样的:

protected void gvMetrics_OnRowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     DataRow _data = ((DataRowView)e.Row.DataItem).Row; 

     // _lastCode is a clas level variable 
     if (_lastCode.ToString() != _data.ItemArray[0].ToString()) 
     { 
      if (_totals == 1) 
      { 
       _lastCode = _data.ItemArray[0].ToString(); 
       e.Row.Cells[0].Text = _data.ItemArray[0].ToString(); 
       _totals++; 
      } 
     } 
     else 
      _totals = 1; // Class level variable initialized to 1. 
    } 
} 

出于某种原因,我不能格式化代码,但你得到的图片。这里我的推理是我将代码分配给类变量,并且每次我都会检查该值是否与当前单元格匹配。如果它匹配跳过写入GridView /页面。这不起作用,所以我想我可以使用一个计数器,在第三次事件后重置为1 - 这再次没有奏效。

我觉得我好亲近,但没有雪茄!我会想象在阳光下这没什么新鲜的,所以如果有人能够提出一个解决方案,我将不胜感激!

回答

2

执行此操作的最佳方法是将第一列变为TemplateField,并添加Literal并执行OnDataBinding事件。

例子:

<asp:TemplateField> 
    <ItemTemplate> 
     <asp:Literal ID="ltYourField" runat="server" 
      OnDataBinding="ltYourField_DataBinding" /> 
    </ItemTemplate> 
</asp:TemplateField> 

然后在您的.cs代码隐藏:

// Create a global to store last value found for the field 
string _lastValueDisplayed = string.Empty; 

落实OnDataBinding

protected void ltYourField_DataBinding(object sender, System.EventArgs e) 
{ 
    Literal lt = (Literal)sender; 
    string displayValue = Eval("yourFieldNameFromResult").ToString(); 
    lt.Text = _lastValueDisplayed.Equals(displayValue) ? 
     string.Empty : displayValue; 
    // store value for checking on next row 
    _lastValueDisplayed = displayValue; 
} 

尽量不要做绑定的东西在OnRowDataBound,因为那么你的代码必须查找控件。如果您使用OnDataBinding将功能与有问题的控件绑定,那么它会将您的代码专门用于您想要的控件,并且不会搜索。

+0

感谢您的意见。剩下的字段会自动解析吗? – Risho

+0

@Risho假设你使用'BoundField'作为其余部分,这些应该没有问题,但是如果你使用'AutoGenerateColumns',你将需要手动定义它们。 – Kelsey

+0

只有前两列是静态的。其余的动态生成基于用户输入usint SQL PIVOT构造,其中一行数据成为单个列,如在这种情况下,每年的月份。 – Risho