搜索后刷新gridview

时间:2012-03-30 13:17:14

标签: asp.net vb.net

我在网格视图上搜索,限制了结果。如果a,我希望网格视图重新填充所有条目。搜索框为空或b。用户点击按钮进行刷新。

Protected Sub btnSeach_Click(sender As Object, e As EventArgs) Handles btnSeach.Click
    StaffDetailsStaffGridView.DataSourceID = ""
    StaffDetailsStaffGridView.DataSource = ObjectDataSource1
    StaffDetailsStaffGridView.DataBind()


    If txtFnameSearch.text = " " Then
        StaffDetailsStaffGridView.DataBind()
    End If
End Sub

Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
    StaffDetailsStaffGridView.DataBind()
End Sub
End Class

StaffDetailsS​​taffGridView.DataBind()显然不起作用。

我该如何正确地做到这一点?

4 个答案:

答案 0 :(得分:1)

重新填充GridView的最佳方法是使用专门用于绑定数据和在需要时调用的方法。

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostback)
        BindGrid();
}

private void BindGrid()
{
    StaffDetailsStaffGridView.DataSource = ObjectDataSource1;
    StaffDetailsStaffGridView.DataBind();

}

protected void btnRefreshSearch_Click(object sender, EventArgs e)
{
    BindGrid(); 
}

protected void btnSeach_Click(object sender, EventArgs e)
{
    if (!String.IsNullOrEmpty(txtFnameSearch.text))
    {
        BindGrid();
    }
}

我假设您是通过ObjectDataSource直接过滤数据。

答案 1 :(得分:0)

您应该再次获取数据源并将其设置为DataSource,然后再次绑定。

像这样的东西

Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click

    Dim searchKey as String 
    searchKey  =txtFnameSearch.Text.Trim()
    Dim staffSearchREsults=MyService.GetSearchResults(searchKey)
    StaffDetailsStaffGridView.DataSource = staffSearchREsults
    StaffDetailsStaffGridView.DataBind()

End Sub

假设MyService.GetSearchResults方法将根据搜索键返回有效的搜索结果。

答案 2 :(得分:0)

这不起作用,因为在回发后,gridview的数据源将丢失。因此,您始终需要在调用DataBind()之前设置数据源。

StaffDetailsStaffGridView.DataSource = ObjectDataSource1
StaffDetailsStaffGridView.DataBind()

您还可以将ObjectDataSource1保存到会话中,稍后再使用它进行绑定:

Session["MyObjectDataSource"] = ObjectDataSource1;

...

Protected Sub btnRefreshSearch_Click(sender As Object, e As EventArgs) Handles btnRefreshSearch.Click
    StaffDetailsStaffGridView.DataSource = Session["MyObjectDataSource"]
    StaffDetailsStaffGridView.DataBind()
End Sub

答案 3 :(得分:0)

如果您使用的是声明性数据源,则只需在DataBind()上再次致电GridView

StaffDetailsStaffGridView.DataBind()