[英]Searching a nested Gridview ASP.net
这是一些入门代码。 但是我不知道循环所有的网格列和单元格是否是搜索数据的有效方法...
在此示例中,代码将停止在网格中第一个找到的搜索词上寻找更多结果。 如果需要最后一个,则应从循环中删除if (searchTermFound == false)
。 如果要匹配多个结果,则应将找到的列和单元格存储在列表或数组中。 使用找到的rowIndexParent
和rowIndexChild
值,可以在所需的行上扩展网格。
private void searchGridView(string searchTerm)
{
int rowIndexParent = -1;
int cellIndexParent = -1;
int rowIndexChild = -1;
int cellIndexChild = -1;
bool searchTermFound = false;
//loop all rows in parent grid
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//remove this if you want the last match displayed as found, not the first
if (searchTermFound == false)
{
//loop all cells in parent grid
for (int j = 0; j < GridView1.Columns.Count; j++)
{
string cellContent = GridView1.Rows[i].Cells[j].Text;
if (cellContent.ToLower().Contains(searchTerm.ToLower()))
{
rowIndexParent = i;
cellIndexParent = j;
searchTermFound = true;
break;
}
}
//find the nested grid and cast it
GridView gv = GridView1.Rows[i].FindControl("GridView2") as GridView;
//loop all rows in child grid
for (int ii = 0; ii < gv.Rows.Count; ii++)
{
//loop all cells in child grid
for (int jj = 0; jj < gv.Columns.Count; jj++)
{
string cellContent = gv.Rows[ii].Cells[jj].Text;
if (cellContent.ToLower().Contains(searchTerm.ToLower()))
{
rowIndexParent = i;
rowIndexChild = ii;
cellIndexChild = jj;
searchTermFound = true;
break;
}
}
}
}
}
//cellIndexParent > -1 means searchTerm is found in parent grid, not child
if (searchTermFound == true && cellIndexParent > -1)
{
Response.Write("Searchterm \"" + searchTerm + "\" found in parent grid: row " + rowIndexParent + ", column " + cellIndexParent + ".");
}
else if (searchTermFound == true)
{
Response.Write("Searchterm \"" + searchTerm + "\" found in child grid: row " + rowIndexChild + ", column " + cellIndexChild + ", parent row " + rowIndexParent + ".");
}
else
{
Response.Write("Searchterm \"" + searchTerm + "\" not found.");
}
}
请注意,这仅适用于BoundField列,不适用于TemplateField和AutoGenerated Columns。 见下文。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<!-- search terms in these columns can be found -->
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:TemplateField>
<ItemTemplate>
<!-- search terms in this column cannot be found -->
<%# DataBinder.Eval(Container.DataItem, "field05").ToString() %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
<Columns>
<!-- search terms in these columns can be found -->
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.