ASP.NET DataSource with parameters for SQL IN clause - asp.net

<asp:SqlDataSource ID="DataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DbConnection %>"
ProviderName="<%$ ConnectionStrings:DbConnection.ProviderName %>"
SelectCommand="select somefield from sometable where somefield in (?)">
<SelectParameters>
<asp:Parameter DefaultValue="" Name="SomeFiedValue" />
</SelectParameters>
</asp:SqlDataSource>
How (from my codebehind) do I allocate a list of values for the parameter in the above SQL query?

try this.
protected void DataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.Parameters["SomeFieldValue"].Value = yourdata;
}
EDIT:
Based on your answers, please have a look at the following website. It explains one way to solve this problem with DB2.
http://www.tek-tips.com/viewthread.cfm?qid=1443561
Based on the comments on that page, a possible solution for your problem could be:
select somefield from sometable where somefield in
(select ? from SYSIBM.SYSDUMMY1)

Related

asp.net insertCommand resulting in NULL values

I have two listboxes whose values are sent into a TableC via a button.
<asp:SqlDataSource ID="sql1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>"
SelectCommand="SELECT [Name] + ' (' + [CNbr] + ')' AS FullName, [CNbr] AS CNum FROM [TableA] ORDER BY [Name]">
</asp:SqlDataSource>
<asp:ListBox ID="lst1" runat="server" DataSourceID="sql1" DataTextField="FullName" DataValueField="CNum" AutoPostBack="true">
</asp:ListBox>
<asp:SqlDataSource ID="sql2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>"
InsertCommand="INSERT INTO [TableB] ([CNbr], [RDate]) VALUES (#CNbr, #RDate)"
<InsertParameters>
<asp:Parameter Name="CNbr" Type="String" />
<asp:Parameter Name="RDate" Type="DateTime" />
</InsertParameters>
<asp:ImageButton ID="ibnCheckOutBtn" runat="server"
ImageUrl="./images/vidCheckOutButton.png" onclick="ibnCheckOutBtn_Click" />
ASPX.CS file:
protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
sql2.Insert();
}
I don't really know C# and my class doesn't cover most C#, so I am looking for a solution that doesn't use a lot of behind-code. The error I get is:
Cannot insert the value NULL into column 'CNbr', table 'TableB'; column does not allow nulls. INSERT fails. The statement has been terminated.
However, nulls should not occur because the values are taken from a fully populated listbox. Help?
You will need to assign the values to sql2 insert parameters in a similar way as follows:
protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
sql2.InsertParameters["CNbr"].DefaultValue = this.FindControl("lst1").SelectedValue;
sql2.InsertParameters["RDate"].DefaultValue = DateTime.Now.ToString();
sql2.Insert();
}

how can i access string variable value of .aspx.cs file in .aspx file

i m getting a string value regression as regression = (Session["Regression"]).ToString(); in .aspx.cs file then i want to use this value in .aspx file in SelectCommand of SqlDataSource property as below
SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%#regression%>'"`
.aspx.cs file page_load method is as below
protected void Page_Load(object sender, EventArgs e)
{
if ((Session["UserName"].ToString()) == string.Empty)
{
Server.Transfer("regressionType.aspx");
}
regression = (Session["Regression"]).ToString();
usrname = (Session["UserName"]).ToString();
DataBind();
}
please suggest me how can i do this?
thanks in advance...
You can you Session Variable's value in your SQLDatasource. Like this Example.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testDatabaseConnectionString %>"
SelectCommand="SELECT * FROM [UserTable] WHERE ([userID] = #UserID)">
<SelectParameters>
<asp:SessionParameter Name="UserID" SessionField="UserID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
let us know any other concerns on this..
add Session paramter to your sql Datasource like this
<asp:SqlDataSource SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%#regression%>'"`>
<SelectParameters>
<asp:SessionParameter SessionField="Regression" Name="ParameterName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Try this:
SelectCommand="SELECT [issue_oid], [issue_num], [regression],
[status], [tested_by], [tested_on], [patch_name], [arrived_on], [previous_info], [comment], [is_duplicate] FROM [itt_monthly_patch_issue_list] where status='Not Tested' and `regression='<%=ReturnRegression()%>'"`
In codebehind:
string regression=null;//Before Page_Load
protected string ReturnRegression()
{
//Write logic here to prevent null being returned
return regression;
}
try this:
public StringBuilder regression = new StringBuilder();
regression.Append((Session["Regression"]).ToString());
Then in the .aspx page (in the selct command), you can use "regression" as:
<% =regression %>

Dynamic query in ASP.Net (WHERE clause in SQLDataSource)

I'm currently trying to loop through an array (two values) and use both values in a query inside the loop. Please see code below. Right now my code doesn't work. I'm trying to populate dynamically the "appType" parameter within the "SelectParameters" tags of the SQLDataSource, but this won't work.
Any suggestion?
<%
Dim appTypes() As String = {"Extranet", "Internet"}
For Each appType As String In appTypes
%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ProviderName = "<%$ ConnectionStrings:CMS.ProviderName %>"
SelectCommand = "SELECT Applications.Name as AppName, Applications.Abbr as AppAbbr, Types.Name as TypeName, Managers.LastName as LastName, Managers.FirstName As FirstName, Managers.EDKeyEmpID as EDKeyID
FROM Types INNER JOIN (Managers INNER JOIN Applications ON Managers.ID=Applications.Manager) ON Types.ID=Applications.Type
WHERE (Types.Name = #appType)
ORDER BY Types.Name, Applications.Name;"
ConnectionString="<%$ ConnectionStrings:CMS %>">
<SelectParameters>
<asp:Parameter DefaultValue="<%=appType%>" Name="appType" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Repeater ID="Repeater1" DataSourceID="SqlDataSource1" runat="server">
<ItemTemplate>
<%#Eval("AppName")%> (<%=appType%>)
</ItemTemplate>
</asp:Repeater>
<% Next %>
Modify your SqlDataSource to have an OnSelecting member:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" OnSelecting="OnSelecting"
Reset your SelectParameters back to normal:
<SelectParameters>
<asp:Parameter Name="appType" Type="String" />
</SelectParameters>
Define this method in your code-behind. Implement the logic as required. Here I've shown a dummy value from your Repeater. It'll be up to you to determine how/where that actually comes from (SelectedItem or something similar).
Protected Sub OnSelecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
e.Command.Parameters("#appType").Value = Repeater1.SomeValue
End Sub

Grab query results from SqlDataSource and store as string

I have a SQL query that will result in one string. Rather than bind a gridview, listview, etc to it and have a single lonely label inside, I just want to store the string (it'll eventually get used later elsewhere). For the life of me I cannot figure this out.
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="select [title] from [books]
where([Genre]=#Genre)
OnSelected="SqlDataSource3_Selected">
<SelectParameters>
<asp:Parameter Name="Title" Direction="ReturnValue" Type="String" />
<asp:ControlParameter ControlID="DropDownList1" Name="genre"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
protected void SqlDataSource3_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
string sqlreturnString = Convert.ToString(e.Command.Parameters["#Title"].Value);
Label3.Text = sqlreturnString;
}
All this does is spit out '0' when I want it to display the title. If I change ["#Title"] to [1], it'll display the Genre. Right now there are only four books, each with a unique genre.
Add a button and write this code in the handler of button's click.
DataSourceSelectArguments sr = new DataSourceSelectArguments();
DataView dv =(DataView) SqlDataSource3.Select(sr);
if(dv.Count!=0)
Label1.Text = dv[0][0].ToString();
I encountered this same issue also when doing C# and ASP.NET, it would be really nice to have a method that dumps out a string of the text results of the query in a SQLDataSource or an AccessDatasource. Until then, Here is an example of the solution I found that works very well:
AccessDataSource MyDataSource = new AccessDataSource("~/App_Data/MyDB.mdb",
"SELECT Name FROM Employees");
DataView MyView = (DataView) MyDataSource.Select(DataSourceSelectArguments.Empty);
lblResults.Text = MyView[0][1].ToString();
This example will also work with SqlDataSource objects.

Using SelectParameters in ASP.NET gives 'Must declare variable' errors

I have an ASP SqlDataSource connected to Sybase DB query, using Select Parameters that are populated by a dropdown:
Dropdown (works OK):
<asp:SqlDataSource ID="dsBondIDList" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [name], [bondID] FROM [bonds]">
</asp:SqlDataSource>
<asp:DropDownList ID="lstBondID" runat="server" DataSourceID="dsBondIDList" DataTextField="name" DataValueField="bondID">
SqlDataSource with parameter:
<asp:SqlDataSource ID="dsBonds" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT [ticker], [name], [isin], [currency],
[stock], [maturity], [bid], [ask]
FROM [bonds] where [bondID] = #bondID">
<SelectParameters>
<asp:ControlParameter Name="bondID" ControlID="lstBondID" PropertyName="SelectedValue" DefaultValue="-1" />
</SelectParameters>
</asp:SqlDataSource>
But I get an error when I try to run it:
ERROR [HY000] [DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]Must declare variable '#bondID'.
Which of course I would get it I ran the sql literally as displayed. I expect the ASP engine to do the substitution before sending the query (and to use the default value of lstBondID if necessary)
Does anybody know why the #bondID is not being substituted with the lstBondID.SelectedValue?
Thanks in advance
Ryan
I just went through this problem 10 minutes ago and here's the fix:
If you need to keep using the ODBC driver you have, change your query to use ? instead of Named Parameters.
SELECT [ticker], [name], [isin], [currency],
[stock], [maturity], [bid], [ask]
FROM [bonds] where [bondID] = ?
The parameters are used in the order they are added to the parameters collection (This gets hairy when you need to use the parameter more than once in your query etc).
Otherwise you can change drivers. Look for sybdrvodb.dll and regsvr32 it. Then setup your DSN and use that.

Resources