Using the username or Page.User.Identity.Name for select parameter
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, ByV开发者_开发知识库al e As EventArgs)
TryCast(LoginView1.FindControl("SqlDataSource1"), SqlDataSource).SelectParameters("username").DefaultValue = Page.User.Identity.Name
End Sub
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:
Protected Sub Login1_LoggedIn(ByVal sender As Object, ByVal e As EventArgs)
Dim login1 As Login = DirectCast(sender, Login)
TryCast(LoginView1.FindControl("SqlDataSource1"), SqlDataSource).SelectParameters("username").DefaultValue
= login1.UserName
End Sub
精彩评论