使用用户名或 Page.User.Identity.Name 作为选择参数
我在 LoginView 控件内有一个登录控件,在登录模板上有一个 gridview 和一个 sqldatasource。
我需要的是使用用户名来过滤该网格视图。但我总是收到错误“对象引用未设置为对象的实例”。我还尝试将 .tostring 添加到 page.user.identity.name
看看下面的代码:
<asp:LoginView ID="LoginView1" runat="server">
<AnonymousTemplate>
<asp:Login ID="Login1" runat="server" OnLoggedIn="Login1_LoggedIn">
</asp:Login>
</AnonymousTemplate>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
ProviderName="<%$ ConnectionStrings:ApplicationServices.ProviderName %>"
SelectCommand="SELECT DISTINCT [UserName], [Date], [TimeIn], [TimeOut], [Total] FROM [attendance] ORDER BY [Date] where username = @username ">
<SelectParameters>
<asp:Parameter Name="username" />
</SelectParameters>
</asp:SqlDataSource>
对于代码隐藏
Protected Sub Login1_LoggedIn(ByVal sender As Object, ByVal e As EventArgs)
TryCast(LoginView1.FindControl("SqlDataSource1"), SqlDataSource).SelectParameters("username").DefaultValue = Page.User.Identity.Name
End Sub
I have a login control inside a loginview control and on the loggedin template, there is a gridview and an sqldatasource.
What I need is to use the username to filter that gridview. But I always get the error Object reference not set to an instance of an object.. I also tried adding .tostring to the page.user.identity.name
Take a look at my code below:
<asp:LoginView ID="LoginView1" runat="server">
<AnonymousTemplate>
<asp:Login ID="Login1" runat="server" OnLoggedIn="Login1_LoggedIn">
</asp:Login>
</AnonymousTemplate>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
ProviderName="<%$ ConnectionStrings:ApplicationServices.ProviderName %>"
SelectCommand="SELECT DISTINCT [UserName], [Date], [TimeIn], [TimeOut], [Total] FROM [attendance] ORDER BY [Date] where username = @username ">
<SelectParameters>
<asp:Parameter Name="username" />
</SelectParameters>
</asp:SqlDataSource>
For the code-behind
Protected Sub Login1_LoggedIn(ByVal sender As Object, ByVal e As EventArgs)
TryCast(LoginView1.FindControl("SqlDataSource1"), SqlDataSource).SelectParameters("username").DefaultValue = Page.User.Identity.Name
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在重新加载页面之前,不会设置 Page.User.Identity.Name。因此它在 LoggedIn 事件中不可用,但您可以简单地使用 Login1.UserName。由于您点击了 LoggedIn 事件,因此已确认您的凭据有效。
在您的情况下,由于登录控件位于 LoginView 控件内部,因此您必须首先获取对该控件的引用,如下所示:
Page.User.Identity.Name is not set until the page is re-loaded. So it is not available in LoggedIn event but instead you can simply use Login1.UserName. Since you hit the LoggedIn event it is confirmed that your credentials are valid.
In your case since the Login Control is inside of LoginView control, you will have to first get reference to that control something like below: