下面是一些讓你開始的代碼。但我不知道循環所有的gridcolumns和cell是否是一種有效的方式來搜索數據...
在這個例子中,代碼將停止在網格中找到的第一個searchterm上尋找更多結果。如果你想最後一次你應該從循環中刪除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.");
}
}
注意,這僅與綁定列列,而不是模板列和自動生成列的作品。見下文。
<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>
所以我會剛剛成立我使用該檢索詞等於搜索字詞文本框? txtSearch.Text = searchTerm;然後在btnSearch_click上調用這個方法? – Norque
這將工作。只要驗證搜索字詞的長度至少爲3個字符,否則您會收到很多誤報。 – VDWWD
有沒有簡單的方法來顯示搜索結果?或者是一點工作?因爲這件事很好用!現在我只需要刷新我的gridview,只顯示找到的信息。 – Norque