<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:arqsi43ConnectionString %>" SelectCommand="SELECT [nome], [votos], [id] FROM [Playlist] WHERE ([semana_votacao] = #semana_votacao)">
<SelectParameters>
<asp:QueryStringParameter Name="semana_votacao"
QueryStringField="SELECT MAX(id) FROM VotacaoSemana" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
I have 2 tables - PlayList and VotacaoSemana.
I need to show on a gridview all values from PlayList that have the attribute semana_votacao equal to the max id from table votacaosemana.
I used the wizard to try to configure it, but I am doing something wrong, because the gridview is empty...
Any Help?
You cannot write sql queries for QueryStringField which is url query string. Change your SelectCommand as follows and no need to have parameters
SelectCommand = "SELECT [nome], [votos], [id] FROM [Playlist]
WHERE [semana_votacao] = (SELECT MAX(id) FROM VotacaoSemana)"
Related
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);
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 just got this message from Visual Studio 2005, when I clicked on the delete command I added to my gridview using the interface for configuring the grid:
Deleting is not supported by data
source 'transactionsSqlDataSource'
unless DeleteCommand is specified.
How can I activate that? I want my user to be able to delete a row when they click on the button Delete.
I already changed the property DeleteCommandType of my SQLDataSource to StoredProcedure.
What else do I need to do?
UPDATE
This is what I did, but I am missing something, I can't compile:
This is what I did at .cs:
public string DeleteCommand { get; set; }
How can I fix that, it says that the get is missing the body. I am not use to ASP.NET. Could you help me fixing this part of my code?
This is what I did at .aspx:
<asp:SqlDataSource ID="transactionsSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:membershipsDBConnectionString %>"
SelectCommand="SELECT [brukerId], [kjoptekvoten], [pengeneutbetalt], [fyringsolje], [biltype], [kjoptid] FROM [Informasjon]" DeleteCommandType="StoredProcedure"
DeleteCommand="DELETE FROM [Informasjon] WHERE fyringsolje='Kull: 2,42 kg';">
</asp:SqlDataSource>
Is the configuration for the datasource correct? Dont worry if you see that the delete command does not use parameters like the one above, it is just for a homework(I only need the query to pass).
UPDATE 2
I keep trying but i cant fix it. I am really newbie in ASP.NET and I am not very familiar with all the terminology. What exactly is happening here? How can I know the name of my store procedure?:
CS:
public string DeleteCommand { get { return DeleteCommand; } set { DeleteCommand = "";}
Aspx:
<asp:SqlDataSource ID="SqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:membershipsDBConnectionString %>"
DeleteCommandType="StoredProcedure" SelectCommand="SELECT [id], [kjoptekvoten], [pengeneutbetalt], [fyringsolje], [biltype], [kjoptid] FROM [Informasjon]"
DeleteCommand="StoredProcedureName">
</asp:SqlDataSource>
When I click on Delete that row needs to be erased from table Informasjon
DeleteCommand="<your stored proc>"
is needed in your SqlDataSource along with any parameters you want, for instance:
<DeleteParameters>
<asp:Parameter Name="myParameter" Type="Int32" />
</DeleteParameters>
which needs to be added in the SqlDatasource tag.
You can either call a stored procedure if you have created one like below :
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
// in the select command or your case delete you just input the name instead of a query
SelectCommand="SELECT * FROM [Table] WHERE [Column1]=#Parameter1 AND [Column2]=#Parameter2 AND [Column3]=#Parameter3;"
DeleteCommand="StoredProcedureName"
// Then ofcourse put the commandtype on storedprocedure but you already have that
DeleteCommandType="StoredProcedure">
// And you can declare the parameters like below
<SelectParameters>
<asp:Parameter Name="Parameter1" Type="String" />
<asp:Parameter Name="Parameter2" Type="Boolean" />
<asp:Parameter Name="Parameter3" Type="String" />
<asp:Parameter Name="Parameter4" Type="Boolean" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="Parameter1" Type="String" />
</DeleteParameters>
</asp:SqlDataSource>
For more information about storedprocedures please read : What is a stored procedure?
Or you can directly call a query like in the example below :
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [informasjon];"
DeleteCommand="DELETE FROM [informasjon] WHERE [id]=#id;">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int" />
</DeleteParameters>
</asp:SqlDataSource>
The connection string is something you will have to provide for yourself. For more info on the connectionstring please read : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=vs.110%29.aspx
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