我有一个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.
}
}
出于某种原因,我无法格式化代码,但你得到了图片。我的理由是,我将代码分配给类变量,并且每个OnRowDataBaound
事件我将检查该值是否与当前单元格匹配。如果匹配则跳过写入GridView
/页面。这没用,所以我想我可以使用一个计数器,在第三次事件后将自身重置为1 - 再次无效。
我觉得我太近了但没有雪茄!我想在阳光下这不是什么新东西,所以如果有人能提出解决方案,我会非常感激!
答案 0 :(得分: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将功能绑定到相关控件,它会将您的代码专门用于您想要的控件,并且不会进行搜索。