Is there a way to define SessionParamters in the SelectParameters of a DataSource that aren't called in the SelectCommand?
I want the parameter to be defined so it can be used later, after initial page generation, but when it's not used in the SelectCommand the DataSource doesn't seem to work - the GridView which calls it appears empty, yet generates fine when the unused Parameters are excluded.
For example, the following definition will fill the GridView successfully:
<asp:SqlDataSource ID="DataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT * FROM Customers WHERE #UsedParameter='Green'">
<SelectParameters>
<asp:SessionParameter Name="UsedParameter" SessionField="Parameter1" />
</SelectParameters>
</asp:SqlDataSource>
Whereas the following would not fill the GridView:
<asp:SqlDataSource ID="DataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT * FROM Customers WHERE #UsedParameter='Green'">
<SelectParameters>
<asp:SessionParameter Name="UsedParameter" SessionField="Parameter1" />
<asp:SessionParameter Name="UnUsedParameter2" SessionField="Parameter2" />
</SelectParameters>
</asp:SqlDataSource>
That is interesting... I think I've seen that problem before when I forgot to remove a parameter. Since you are likely going to change the select command later to use the other parameter, why don't you just add the parameter at that time?
VB
Dim p As New SessionParameter("UnUsedParameter2", "Parameter2")
DataSource1.SelectParameters.Add(p)
C#
SessionParameter p = new SessionParameter("UnUsedParameter2", "Parameter2")
DataSource1.SelectParameters.Add(p);
Related
I am learning ASP.NET(C#) and came across this code:
<asp:DropDownList
id="ddlMovieCategory"
DataSourceID="srcMovieCategories"
DataTextField="Name"
DataValueField="Id"
Runat="server" />
<asp:Button
id="btnSelect"
Text="Select"
Runat="server" />
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
CssClass="gridView"
Runat="server" />
<asp:SqlDataSource
id="srcMovieCategories"
SelectCommand="SELECT Id, Name FROM MovieCategories"
ConnectionString="<%$ ConnectionStrings:Movies %>"
Runat="server" />
<asp:SqlDataSource
id="srcMovies"
SelectCommand="SELECT Title,Director FROM Movies
WHERE CategoryId=#Id"
ConnectionString="<%$ ConnectionStrings:Movies %>"
Runat="server">
<SelectParameters>
<asp:ControlParameter
Name="Id"
ControlID="ddlMovieCategory"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
I am wondering How the # symbol in the last control's SelectCommand work. It works as expected but I don't understand how it gets the value following the # i.e. if it is to use a variable which is escaped in ASP tag then how does it know that Id refers to the DropDownList's currently selected item.
Edit: I think I might have found the solution. I think it's from this bit of code, Am I correct:
<asp:ControlParameter
Name="Id"
ControlID="ddlMovieCategory"
PropertyName="SelectedValue" />
</SelectParameters>
The following string
"SELECT Title,Director FROM Movies WHERE CategoryId=#Id"
represents a parameterized sql query. The value of parameter Id, #Id, would be assigned to CategoryId, before this query is sent to database, in order to be executed.
Parameterized queries are the first thing we use, in order we avoid SQL injections.
I'm doing the following query, and trying to use a code that come from a previous query.
But is giving me the following error: The server tag is not well formed.
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:TesteConnectionString %>" SelectCommand="SELECT * FROM [Equipa] where idAssemb=1 and idDept=<%# Eval("idDept") %>"></asp:SqlDataSource>
I'm using C# in Web forms asp.net
Can somebody help me on this?
Eval is used in DataBound controls to evaluate a field value in a row from the data source. You are trying to use it inside a Data Source control itself (SQLDataSource in this case). You should use parameterized query by specifying the value of parameter inside SelectParameters tag like this:-
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:TesteConnectionString %>"
SelectCommand="SELECT * FROM [Equipa] where idAssemb=1 AND idDept=#DeptId>
<SelectParameters>
<asp:ControlParameter ControlID="lblDeptId" Name="DeptId"
PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
Please note, here I have shown the example of a control present inside your WebForm. You can specify where the value of DeptId is coming from via Cookie, QueryString, Form, Session etc.
I'm creating a ListView in ASP.NET and have based mine on the example given by CodeProject here. I want to make the Select Command of the SqlDataSource dynamic so that a value is generated from one provided from the session. Ive tried a fue different possibilities, here is an example of what I want:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = <%# Eval("value") %> " >
</asp:SqlDataSource>
How would I pass such a value using ASP? Ive also tried creating the query in the C# back page and linking to it like SelectCommand = "<%# Eval("Query") %>" and also by using the #value syntax. neither work!
This should do the trick. Define a SessionParameter as follows and make sure Name=Sql parameter name and SessionField is same as your session field. DBType and DefaultValue as required...
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
SelectCommandType="Text"
ConnectionString="<%$ ConnectionStrings:TestDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = #ParaName"
<SelectParameters>
<asp:SessionParameter
Name="ParaName"
SessionField="YourSessionFieldName"
DbType="String"
DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
Replace with
SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = #Name"
And define your #Name as parameter
<SelectParameters>
<asp:Parameter DefaultValue="<%# Eval("Query") %>" Name="Name" DbType="..." />
</SelectParameters>
The solutions provided are very good. It should also be noted that trying to place your "value" directly in the query, you are opening yourself up to SQL injection attacks. Using the select parameters prevents and protects you from this.
I had the same issue and my lazy approach to solving it was to do as follows:
command.CommandText = item.Query.Replace("#Value", Value);
command.ExecuteNonQuery();
Dirty, easy and most likely not the proper way to do it.
I would really recommend against using a SqlDataSource control. A SqlDataSource provides very little in the realm is reuse.
Programatically make the DB call
If you make the call in a separate class (or even better in a DAL) you will be able to use it across multiple pages with ease. Also, when a change occurs to your query you will just have to change it in one place.
Here is a sample below that uses the Entity Framework to access the database
Mark up
<asp:DropDownList ID="ddlTest" runat="server"></asp>
Code Behind
public List<Record> GetAllRecordsByUserName(string credentials)
{
List<Record> recordList;
using (CustomEntities context = new CustomEntities())
{
IQueryable<Record> recordQuery = from records in context.Records
where records.UserName == credentials
select records;
recordList = recordQuery.ToList<Record>();
}
return recordList;
}
public void ValidateAndBind(string username)
{
List<Record> recordList = GetAllRecordsByUserName(username);
// Do validation here
ddlTest.DataSource = recordList;
ddlTest.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
ValidateAndBind("test.username");
}
Another way to achieve your goal without code behind is using an Hidden Field and doing the following:
<asp:HiddenField runat="server" ID="HfieldID" Value='<%# Eval("value")%>'/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestDatabaseConnectionString %>" SelectCommand="SELECT * FROM [Contacts] WHERE [Name] = #Name">
<SelectParameters>
<asp:ControlParameter Name="Name" PropertyName="Value" ControlID="HfieldID" DbType="String" />
</SelectParameters>
</asp:SqlDataSource>
Be sure to put this before any controls that will use this SqlDataSource.
I have a SqlDataSource SelectCommand on my .aspx page.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT * FROM [UserResult]"
OnSelecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>
This statement will grep a list of data from the table UserResult.
However I would only want to list specific results which belongs to the user.
I have attached a column in the UserResult table which is username, and I tried to form an sql statement like this but it seems to search for user User.Identity.nAME :
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SODConnectionString %>"
SelectCommand="SELECT * FROM [UserResult] WHERE [username] LIKE 'User.Identity.Name'";"
OnSelecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>
May I know how can I do it?
Update:
From solution from Curt, I have tried to implement the following:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SODConnectionString %>"
SelectCommand="SELECT * FROM [UserResult] WHERE [username]=#username"
OnSelecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:Parameter Name="username" Type="String" DefaultValue='<%=User.Identity.Name %>' />
</SelectParameters>
</asp:SqlDataSource>
However I am still not able to retrieve data according to the username.
I tried to hard code a username into the username parameter and it worked:
Anyone could help?
<asp:Parameter Name="username" Type="String" DefaultValue="james" />
Your statement is looking for User.Identity.Name because this is set as a string.
Try using code blocks:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SODConnectionString %>"
SelectCommand="SELECT * FROM [UserResult] WHERE [username]=#username"
OnSelecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:Parameter Name="username" Type="String" DefaultValue='<%=User.Identity.Name %>' />
</SelectParameters>
</asp:SqlDataSource>
Embedded Code Blocks in ASP.NET Web Pages
It is not necessary to declare a Default Value in .aspx file. You can only add to the code behind file.
protected void Page_Init(object sender, EventArgs e)
{
SqlDataSource1.InsertParameters["UserName"].DefaultValue = User.Identity.Name;
}
I have an SqlDataSource in a page, which will display different results depending on 1 or 2 query strings, and/or a filter textbox.
Here is my SqlDataSource and filters:
<asp:SqlDataSource ID="sdsAudits" runat="server"
ConnectionString="<%$ ConnectionStrings:constring %>"
SelectCommand="SELECT * FROM [Audit]" FilterExpression="source = {0} AND customer = {1} AND (itemID like '%{2}%' OR parentID like '%{2}%')">
<FilterParameters>
<asp:QueryStringParameter Name="source" QueryStringField="source" />
<asp:QueryStringParameter Name="customer" QueryStringField="customer" />
<asp:ControlParameter Name="txtFilter" ControlID="txtFilter" PropertyName="Text" />
</FilterParameters>
But for some reason, the filtering for any of the 3 possible filters don't work. I tried taking out the 2 query string filters, and leaving just the textbox filter, and it worked fine then - so I'm guessing my filter expression is wrong?
Any ideas guys? Remember all 3 filters could be 'active' at once, if they have the 2 query strings and have typed into the textbox, or they could be none at all, or of course anything in between.
Filter is intended to work in DataSet mode - data is retrieved into memory, and then filtered. Not very efficient - much better to use parameters in the select command itself, like so:
<asp:SqlDataSource ID="sdsAudits" runat="server"
ConnectionString="<%$ ConnectionStrings:constring %>"
SelectCommand="SELECT * FROM [Audit] where source = #source AND customer = #customer AND (itemID like '%' + #txtFilter + '%' OR parentID like '%'+#txtFilter+'%')">
<SelectParameters>
<asp:QueryStringParameter Name="source" QueryStringField="source" />
<asp:QueryStringParameter Name="customer" QueryStringField="customer" />
<asp:ControlParameter Name="txtFilter" ControlID="txtFilter" PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
or just add
DataSourceMode="DataSet"
to your SqlDataSource tag