Sub Page_Load(...)
If Not IsPostBack Then
BindData()
End If
gvCustomers.AllowPaging = False
BindData()
lblResult.Text = gvCustomers.Rows.Count.ToString & " records found "
gvCustomers.AllowPaging = True
BindData()
End Sub
Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClear.Click
' Simple clean up text to return the Gridview to it's default state
searchBox.Text = ""
SearchString = ""
BindData()
End Sub
然后在gridview标记上:
<asp:Label ID="lblResult" style ="font-weight:bold; " runat="server"
CssClass="style26"></asp:Label>
... another markup goes here ...
<asp:button ID="btnClear" Text="Reset" runat="server" />
我们想要做的是在页面加载时显示gridview上的记录总数。 就页面加载而言,这种方法很好。搜索记录时,它会显示找到的正确记录数。
现在出现了问题部分。如果单击“重置”按钮控件,gridview应默认返回到记录总数。按一次“重置”按钮后,它不会重置为原始总数。
在页面重新加载gridview上的记录总数之前,您必须按两次“重置”按钮。
任何想法如何解决这个问题,以便在第一次按下重置按钮时重新加载? 非常感谢
Private Sub BindData()
Dim strSearch As String
'Protect against SQL Injection
strSearch = Replace(searchBox.Text, "'", "''", 1, -1, 1)
Dim query As String = "SELECT r.RoleId,l.LoginId, l.fullname,l.UserName,r.UserRoles FROM tblLogin l Inner Join tblRoles r on l.rights = r.roleId WHERE l.fullname LIKE '%" & strSearch & "%' "
Dim cmd As New SqlCommand(query)
gvCustomers.DataSource = GetData(cmd)
gvCustomers.DataBind()
End Sub
答案 0 :(得分:0)
我建议不要一次又一次地重新绑定数据源,而是建议调用方法dataBind()
。因此,您首先在gridView中设置记录数会变得更加清晰,之后重新绑定它以显示所有数据
我认为这是一个事件顺序问题。您单击的每个按钮都将返回到服务器,并首先调用您的PageLoad
eventHandler。之后,您的btnClear_Click
将被调用。
所以我希望我确实帮到你并建议以下代码:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
BindData()
End If
' gvCustomers.AllowPaging = True ' I would set this in markup!!
End Sub
Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClear.Click
' Simple clean up text to return the Gridview to it's default state
searchBox.Text = ""
BindData()
End Sub
根据给定的细节重写答案!我假设GetData(cmd)
返回一个DataTable。如果我错了请告诉我。
Sub BindData()
' use SQL-Parameter instead - see below
Dim query As String = "SELECT r.RoleId,l.LoginId, l.fullname,l.UserName,r.UserRoles FROM tblLogin l Inner Join tblRoles r on l.rights = r.roleId WHERE l.fullname LIKE '%@searchText%' "
Dim cmd As New SqlCommand(query)
cmd.Parameters.Add("@searchText", SqlDbType.VarChar, 80).Value = searchBox.Text;
Dim dt as DataTable
dt = GetData(cmd)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
lblResult.Text = dt.Rows.Count.ToString & " records found "
End Sub
在此代码中,您的BindData()
将在page_load上调用一次,之后仅在您必须重新绑定数据时调用(例如:搜索,重置)
答案 1 :(得分:0)
为什么你可以使用Container.DataItemIndex
<asp:TemplateField HeaderText="Slno" Visible="false">
<ItemTemplate>
<div style="margin-top: 0px; color: Black;">
<asp:Label ID="txtslno" ForeColor="#000f9f" Font-Size="8" runat="server" Text='<%# Container.DataItemIndex+1 %>'></asp:Label>
</div>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="30px" />
</asp:TemplateField>