SqlDataSource won't retrieve logged in user's data from database? - asp.net

I tried retrieving the user's data based on the logged in UserId, but no progress. Any suggestions?
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Get a reference to the currently logged on user
MembershipUser currentUser = Membership.GetUser();
// Determine the currently logged on user's UserId value
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Assign the currently logged on user's UserId to the #UserId parameter
e.Command.Parameters["#UserId"].Value = currentUserId;
}
And this is the SqlDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString='<%$ ConnectionStrings:NaviConnectionString %>'
SelectCommand="SELECT [UserId], [FirstName], [LastName] FROM [UserProfiles] WHERE ([UserId] = #UserId)">
<SelectParameters>
<asp:Parameter Name="UserId" Type="String"></asp:Parameter>
</SelectParameters>
</asp:SqlDataSource>
And this is the GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKFFeyNames="UserId" DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display."
DataKeyNames="UserId">
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId" SortExpression="UserId" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
</Columns>
</asp:GridView>
There are no data records to display.
However, when I execute the code in query builder, it works.
So I need to get the UserId manually from the database.
Then go to the query builder then execute then paste the userid in to the value of UserID.
Then it displays the correct data based on the UserId:
I also tried changing it to this:
<SelectParameters>
<asp:Parameter Name="UserId" Type="Empty" DbType="Guid"></asp:Parameter>
</SelectParameters>

You should set a break point and see if currentUserId is populated. I believe that it is. If so, then retrieving the UserId is not the problem, but instead the problem is setting the parameter value or selecting the data.
I think you need to change the type of your parameter from string to Guid
<SelectParameters>
<asp:Parameter Name="UserId" Type="Guid"></asp:Parameter>
</SelectParameters>

Just Change This:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Get a reference to the currently logged on user
MembershipUser currentUser = Membership.GetUser();
// Determine the currently logged on user's UserId value
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Assign the currently logged on user's UserId to the #UserId parameter
e.Command.Parameters["#UserId"].Value = currentUserId.ToString();
}

in parameter types there is no guid option. (Also in above codes sql data source has not been set SqlDataSource1_Selecting.) How could it be answer? Just declare parameter name and its ok.
<asp:Parameter Name="UserId"></asp:Parameter>

Related

Storing another control value in a field of DetailsView Insert Interface

I have an asp.net program.
Here I want to keep Insert Facility of the Details view. But in the interface I want to keep the 'UserName' attribute of the new Record as fixed and same as the UserName of the Logged in user. I also want to check it on Server side whether it corresponds to the logged in user's username.
How can I achieve this functionality.
I have made the BoundField ReadOnly. But I can't find anything else suitable for this functionality.
In your .aspx do the following:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" OnInserting="SqlDataSource1_Inserting">
<InsertParameters>
<asp:Parameter Type="String" Name="Username" />
//Place other parameters here
</InsertParameters>
</asp:SqlDataSource>
In your code behind:
protected void SqlDataSource1_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
SqlDataSource1.InsertParameters["Username"].DefaultValue = Context.User.Identity.Name;
}

How to load Data from a second table in GridView

i have to tables: Users and PrivateMessages.
Users has UserID and Username.
PrivateMessages has the coloumns PMID and Text and SenderID.
(of course it has much more but to explain the problem, its enough)
Now I have a DataSource and a method like this:
public static List<UserPM> GetAllPMsAsSender(Guid userID)
{
using (RPGDataContext dc = new RPGDataContext())
{
return (from a in dc.UserPMs where a.Sender == userID && !a.IsDeletedSender orderby a.Timestamp select a).ToList();
}
}
and bind it to the ObjectDataSource with is bound to the Grid View.
The Grid view now looks like these:
<asp:ObjectDataSource ID="odsOutcome" runat="server"
SelectMethod="GetAllPMsAsSender" TypeName="DAL.PMDAL">
<SelectParameters>
<asp:CookieParameter CookieName="UserID" DbType="Guid" Name="userID" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView ID="gridOut" runat="server" AutoGenerateColumns="False"
DataSourceID="odsOutcome">
<Columns>
<asp:BoundField DataField="PMID" HeaderText="PMID" SortExpression="PMID" />
<asp:BoundField DataField="Text" HeaderText="Text" SortExpression="Text"/>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
</Columns>
</asp:GridView>
So how I can get the Username in this field instead the UserID?
Try using join and select the user name too for your object data source and use the user name to display it instead of user id.
Refer this link How to do a join in linq to sql with method syntax?

DataGridView + SqlData Source Madness

I am trying to populate data from a table created in aspnetdb.mdf that has game data stored in it, which has a uniqueidentifier that is UserId that is the users Asp Membership UserId. I want to select the users data from the table using a SqlDataSource and populate it into the DataGridView.
I have read thread after thread, and MSDN documentation, and for the life of me I can't get this joker to work. The DataGridView isn't even displayed, just a blank screen. In the designer I can see the columns I wan't to select.. Here is the code. If anyone has an idea, answer, or anything I would greatly appreciate it.
I have tried switching the parameter data types and just about anything I can think of, but that didn't work
In code behind:
protected void userGameData_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
MembershipUser User = Membership.GetUser();
object UserGUID = User.ProviderUserKey;
userGameData.SelectParameters["UserId"].DefaultValue = UserGUID.ToString();
}
in aspx
<form id="frm" runat="server">
<asp:SqlDataSource ID="userGameData" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [cycleday], [playerwins], [housewins], [gametype], [gamedate], [phase] FROM [GameData] WHERE ([UserId] = #UserId)" OnSelecting="userGameData_Selecting">
<SelectParameters>
<asp:Parameter Name="UserId" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="rawGameResults" runat="server" AutoGenerateColumns="False" DataSourceID="userGameData">
<Columns>
<asp:BoundField DataField="cycleday" HeaderText="cycleday" SortExpression="cycleday" />
<asp:BoundField DataField="playerwins" HeaderText="playerwins" SortExpression="playerwins" />
<asp:BoundField DataField="housewins" HeaderText="housewins" SortExpression="housewins" />
<asp:BoundField DataField="gametype" HeaderText="gametype" SortExpression="gametype" />
<asp:BoundField DataField="gamedate" HeaderText="gamedate" SortExpression="gamedate" />
<asp:BoundField DataField="phase" HeaderText="phase" SortExpression="phase" />
</Columns>
</asp:GridView>
</form>
Maybe the bind is not working from the markup, I would try it from code-behind
string sql = "SELECT [cycleday], [playerwins], [housewins], [gametype], [gamedate], [phase] FROM [GameData] WHERE UserId = (SELECT [UserId] FROM aspnet_users WHERE UserName = '" & User.Identity.Name & "')";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
{
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
DataTable myTable = new DataTable();
myTable.Load(myReader);
myConnection.Close();
YourDataGridView.DataSource = myTable;
YourDataGridView.DataBind();
}
}
}
Set connectionString to the CS you are using in your project :)

Passing C# variable into aspx Source Sql Query

I'm trying to do a messaging system where the inbox is a gridview of all the messages associated with a user's ID. I have a global get method in C# to get the user currently signed in. I'm wondering how to tie this back so that the database only shows the data I want it to.
In my .aspx.cs file, I have something like:
protected void Page_Load(object sender, EventArgs e)
{
int userInSess = getLoggedInUser();
Session["user"] = user;
}
In the source file, I have something like:
<asp:SqlDataSource ID="ProjectDB" runat="server"
ConnectionString="<%$ ConnectionStrings:ProjectConnectionString %>"
SelectCommand="SELECT [SentByUserName], [Subject], [CreateDate] FROM [Messages] WHERE (ReceivedByUserID = #user) ORDER BY [CreateDate] DESC">
<SelectParameters>
<asp:SessionParameter Name = "user" />
</SelectParameters>
</asp:SqlDataSource>
I know this is wrong but I can't seem to find clear answer on how to exactly do this. Any help would be greatly appreciated.
Thanks
You need to reference the value stored in the session with:
<asp:SessionParameter Name="User" SessionField="user" />
Note the addition of SessionField attribute.
SqlDataSource control only uses Name="User" of the Parameter object to match a #user placeholder in SQL query

asp.net sqldatasource detailview: how to set proper select statement

My page load event looks like this....
SqlDataSource1.ConnectionString = Connection.ConnectionStr;
SqlDataSource1.SelectCommand = "select firstname,lastname from customer";
SqlDataSource1.InsertCommand = "CustRec_iu";
SqlDataSource1.InsertCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDataSource1.InsertParameters.Clear();
SqlDataSource1.InsertParameters.Add(new Parameter("firstname", DbType.String));
SqlDataSource1.InsertParameters.Add(new Parameter("LastName", DbType.String));
SqlDataSource1.InsertParameters.Add(new Parameter("Active",DbType.Int16,"1"));
The detailview control setting looks like this....
<asp:DetailsView ID="dvCustDetails1" runat="server" AutoGenerateRows="False"
DataSourceID="SqlDataSource1" Height="149px" Width="469px"
OnItemInserted=dvCustDetails1_ItemInserted
>
<Fields>
<asp:BoundField DataField="FirstName" HeaderText="First Name"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name"
SortExpression="LastName" />
<asp:CommandField ButtonType="Button" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
Right after insert functionality is done, I would like to capture the custid from customer table which is identity column, some how extract it and select table with that record like
select * from customer where custid = #custid.
Then after the control renders after insert, I would like it to show the newly inserted record based on the above select statement.
Also, I would like detailsview to show update button so I could update the record.
How would i accomplish that??
I find very little documentation out there in google search or even print books.
You want to use the sqldatasource's OnSelected event with a return parameter from the SQL call.
Add this to the sqldatasource
OnSelected ="sqlds_Selected"
and implement it something like:
protected void sqlds_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
//get the command object from the arg and
//then you can get to the parameter value
e.Command.Parameters["#CustomerID"].Value
//then set this to your detailsview key
}

Resources