using session variable in aspx page in sql query - c#

I have the sqldatasource in aspx page and in the query I want to use one parameter i.e. coming from session.
Below is my code.Please help me out.
<asp:SqlDataSource runat="server" ID="MySQLData2"
ConnectionString='<%$ConnectionStrings:ConnectionString %>'
ProviderName="MySql.Data.MySqlClient"
SelectCommand="SELECT * FROM tablename WHERE id="Here I want to use session variable"" />

Try this
<asp:SqlDataSource runat="server" ID="MySQLData2"
ConnectionString='<%$ConnectionStrings:ConnectionString %>'
ProviderName="MySql.Data.MySqlClient"
SelectCommand="SELECT * FROM tablename WHERE id=#SessionVar">
<SelectParameters>
<asp:SessionParameter Name="SessionVar" SessionField="SessionVariableName" ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>

This MSDN article should get you what you need. Basically you would define your SelectCommand with the parameter placeholder, "?", and then define your SelectParameters collection with an entry for your SessionParameter.

Using parameters is rather simple:
<asp:SqlDataSource id="Employees" runat="server"
ConnectionString="<%$ ConnectionStrings:Northwind%>"
SelectCommand="SELECT LastName FROM Employees WHERE Title = #Title">
<SelectParameters>
<asp:ControlParameter Name="Title"
ControlID="DropDownList1"
PropertyName="SelectedValue"/>
</SelectParameters>
</asp:sqldatasource>
Just replace the value of parameter with your variable:
<%= Sessiom[variable_name] %>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=LAZY-PC;Initial Catalog=Test;Integrated Security=True"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [C] WHERE ([C#] = #column1)">
<SelectParameters>
<asp:SessionParameter Name="column1" SessionField="id" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

Johnny_D's answer is pretty much spot on, but I'd like to point out that there's a SessionParameter class that you can use for this:
<asp:SqlDataSource runat="server" ID="MySQLData2"
ConnectionString='<%$ConnectionStrings:ConnectionString %>'
ProviderName="MySql.Data.MySqlClient"
SelectCommand="SELECT * FROM tablename WHERE id= ?" />
<SelectParameters>
<asp:SessionParameter
Name="id"
SessionField="SessionVariableName"
DefaultValue="0" />
</SelectParameters>
</asp:SqlDataSource>

Related

Can I use the result of an sqldatasource (a simple string) to use it as a parameter of another sqldatasource?

<asp:SqlDataSource ID="UsersUsernameSQL" runat="server"
ConnectionString="<%$ ConnectionStrings:UserQueries %>"
ProviderName="<%$ ConnectionStrings:UserQueries.ProviderName %>"
SelectCommand="SELECT "FIRSTNAME" FROM "USERS" WHERE ("USERNAME" = ?)">
<SelectParameters>
<asp:ControlParameter ControlID="UsersNameLabel" Name="USERNAME" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
This is my code. My query is that I want to select a name where the username equals with the result of the other SqlDataSource (this one works fine, I checked it)
So can I set the result of the datasource as a parameter? And if yes, then how?

how to get AspNet Identity User ID directly in .aspx?

I´m developing a Web Forms application using VS 2013. In "MyReports.aspx" I want the user to see only the reports that were issued by him/her. In the SqlDataSource SelectParameters I defined the UserID Parameter and then pass the UserId in the codebehind. But, How can I do it directly in the aspx?
I´ve tried adding the Microsoft.AspNet.Identity namespace trough
<%# Import Namespace="Microsoft.AspNet.Identity" %>
And then setting the parameter like:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT * FROM [ReportsByIssuingUserView] WHERE ([UserID]=#UserID)">
<SelectParameters>
<asp:Parameter Name="UserID" Type="String" DefaultValue="<%: Context.User.Identity.GetUserId() %>"/>
</SelectParameters>
</asp:SqlDataSource>
With no luck...
My code right now is the following and works great:
ASPX:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT * FROM [ReportsByIssuingUserView] WHERE ([UserID]=#UserID)">
<SelectParameters>
<asp:Parameter Name="UserID" Type="String"/>
</SelectParameters>
</asp:SqlDataSource>
CS:
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["UserID"].DefaultValue = Context.User.Identity.GetUserId();
}
Is there any way to do it without using the codebehind?
Thanks!
Use the <%= Context.User.Identity.GetUserId() %> expression syntax inline in your ASPX page.

Create Grid view with master page in asp

i am new in asp, i create a grid view with master page. but it show an error in connection string. can anyone help me please?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
AutoGenerateEditButton="true" AutoGenerateDeleteButton="false"
DataSourceID="SqlDataSource1" Font-Names="Arial" Font-Size="Smaller" DataKeyNames="Logid" >
<columns>
<asp:BoundField DataField="Logid" HeaderText="Logid" SortExpression="Logid" />
<asp:BoundField DataField="Username" HeaderText="Username" SortExpression="Username" />
<asp:BoundField DataField="PASSWORD" HeaderText="PASSWORD" SortExpression="PASSWORD" />
<asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
<asp:BoundField DataField="E_MAIL" HeaderText="E_MAIL" SortExpression="E_MAIL" />
</columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1"runat="server" ConnectionString="<%$ ConnectionString:SaqibConnectionString %>"
SelectCommand="SELECT [Logid], [Username], [PASSWORD], [Time_Logged_in], [Time_Logged_Out], [Status], [Date_Logged_in], [E_MAIL]"
UpdateCommand="Update Log_Users SET Logid=#Logid, Username=#Username, PASSWORD=#PASSWORD, Status=#Status, E_mail=#E_mail"
DeleteCommand="DELETE FROM Log_Users WHERE Logid = #Logid">
<UpdateParameters>
<asp:Parameter Name="Logid" />
<asp:Parameter Name="Username" />
<asp:Parameter Name="PASSWORD" />
<asp:Parameter Name="Status" />
<asp:Parameter Name="E_MAIL" />
</UpdateParameters>
</asp:SqlDataSource>
</asp:Content>
Are you sure it's not something simple like the space between ID="SqlDataSource1" and runat="server" bit.
This would cause the error "Server Tag is not well formed" error.
Connection string name should be match with what you have given in web config so,
change ConnectionString="<%$ ConnectionString:SaqibConnectionString %>" to
ConnectionString="<%$ ConnectionStrings:db %>"
or change the name in configuration file which given to your connection string as SaqibConnectionString
Update:
ConnectionString="<%$ ConnectionString:SaqibConnectionString %>"
/\
you missed `s` here
You made mistake on Connection String setting, it should be ConnectionStrings, note that s at the end
try below
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommand="SELECT [Logid], [Username], [PASSWORD], [Time_Logged_in], [Time_Logged_Out], [Status], [Date_Logged_in], [E_MAIL] from Log_Users"
UpdateCommand="Update Log_Users SET Logid=#Logid, Username=#Username, PASSWORD=#PASSWORD, Status=#Status, E_mail=#E_mail"
DeleteCommand="DELETE FROM Log_Users WHERE Logid = #Logid"
ConnectionString="<%$ ConnectionStrings:db %>">
<DeleteParameters>
<asp:Parameter Name="Logid" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Logid" />
<asp:Parameter Name="Username" />
<asp:Parameter Name="PASSWORD" />
<asp:Parameter Name="Status" />
<asp:Parameter Name="E_MAIL" />
</UpdateParameters>
</asp:SqlDataSource>
As seen above your connectionstring name is db but you are using SaqibConnectionString as connection string.so use ConnectionString="<%$ ConnectionString:db %>" in place of
ConnectionString="<%$ ConnectionString:SaqibConnectionString %>"
Update1
and your select statement is not right
SelectCommand="SELECT [Logid], [Username], [PASSWORD], [Time_Logged_in], [Time_Logged_Out], [Status], [Date_Logged_in], [E_MAIL]"
select statement should be
select [Logid], [Username], [PASSWORD], [Time_Logged_in], [Time_Logged_Out], [Status], [Date_Logged_in], [E_MAIL] from Log_Users you are missing from tablename in your select statement
Update2
you do not have space between ID="SqlDataSource1" and runat="server"

Sqldatasource where parameter

I have a sqldatasource, in select command i have #status parameter. The parameter take the value from the textbox at runtime.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [project_details] WHERE ([status] = #status)"
FilterExpression="title='{4}'"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
EnableCaching="True">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" Name="status" PropertyName="Text" ConvertEmptyStringToNull="false"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
my problem is that when i run the page without entring the parameter in text box sqldatasource is not returing any row.
Looking at the documentation on MSDN, you have to alter how you have setup the SqlDataSource.
Try this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [project_details]"
FilterExpression="title='{0}'"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
EnableCaching="True">
<FilterParameters>
<asp:ControlParameter ControlID="TextBox1" Name="status" PropertyName="Text" ConvertEmptyStringToNull="false" Type="String" />
</FilterParameters>
</asp:SqlDataSource>
I have removed the Where clause from the query as this will be applied by the filter expression. Also, I have changed the filter expression from title='{4}' to title='{0}'. The documentation states that the number is a placeholder to an item in the FilterParameters collection.
Updated
I have also changed the SelectParameters to FilterParameters
Update 2
I have created a working example to finish of this answer. This will filter the Title column using the text from the text box. If this text box is empty it will return all the rows from the table (a scary thought but OK for this example). It is querying the AdventureWorks database for which I set a connection string called AWorks.
<asp:SqlDataSource ID="SqlDataSource1"
ConnectionString="<%$ ConnectionStrings:AWorks %>"
SelectCommand="SELECT ContactId, Title, FirstName, LastName FROM Person.Contact"
FilterExpression="Title='{0}'"
runat="server">
<FilterParameters>
<asp:ControlParameter Name="Title" ControlID="txtTitle" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
<asp:TextBox runat="server" Id="txtTitle"></asp:TextBox>
<asp:Button runat="server" UseSubmitBehavior="true" Text="Submit" />
<asp:GridView
DataSourceID="SqlDataSource1"
AutoGenerateColumns="false"
runat="server">
<Columns>
<asp:BoundField Visible="false" DataField="ContactId"></asp:BoundField>
<asp:BoundField Visible="true" DataField="Title"></asp:BoundField>
<asp:BoundField Visible="true" DataField="FirstName"></asp:BoundField>
<asp:BoundField Visible="true" DataField="LastName"></asp:BoundField>
</Columns>
</asp:GridView>
try a condition like this:
(#Status is null or #Status ='' Or Status = #Status)
set ConvertEmptyStringToNull="true" and then try....
Add CancelSelectOnNullParameter="false" to your SqlDataSource.

Using a line of code from codebehind in actual HTML page

I have a database connection which takes an input from the querystring to access the appropriate data. However i have now upgraded things by encoding this data. As a result i now need to run the QueryString value through a function to unencode it.
At present i have this code for the DataSource:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:spareathoughtConnectionString %>"
SelectCommand="campaign_Statistics" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:QueryStringParameter DefaultValue="0" Name="tmp_Campaign"
QueryStringField="camp" Type="Int64" />
</SelectParameters>
</asp:SqlDataSource>
The QueryString value is 'camp'.
In my code behind i would process this value via the following code;
Convert.ToInt64(HttpUtility.UrlDecode(TamperProofQueryString.decode(Request.QueryString["camp"])))
So, how can incorporate the above line of code into the datasource? ie i need to effectively replace 'camp' with 'Convert.ToInt64(HttpUtility.UrlDecode(TamperProofQueryString.decode(Request.QueryString["camp"])))'
I hope this makes sense?
Thanks
Change it to a plain <asp:Parameter rather than a <asp:QueryStringParameter. Then handle the OnSelecting event for the datasource. You should be able to set the parameter value for the SqlCommand in your code-behind there.
In the aspx markup:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:spareathoughtConnectionString %>"
SelectCommand="campaign_Statistics" SelectCommandType="StoredProcedure"
OnSelecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:Parameter DefaultValue="0" Name="tmp_Campaign" Type="Int64" />
</SelectParameters>
</asp:SqlDataSource>
In the code-behind:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters["#tmp_Campaign"].Value = Convert.ToInt64(TamperProofQueryString.decode(HttpUtility.UrlDecode(Request.QueryString["camp"])));
}
Also, looking at that, shouldn't you UrlDecode before the TamperProof decode?
If you want to do all of it without a codebehind, you could do something like:
<asp:SqlDataSource
ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:spareathoughtConnectionString %>"
SelectCommand="campaign_Statistics" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
<%
SqlDataSource1.SelectParameters.Add(
"tmp_Campaign",
Convert.ToString(HttpUtility.UrlDecode(TamperProofQueryString.decode(Request.QueryString["camp"]))));
%>

Categories

Resources