Dynamic query in ASP.Net (WHERE clause in SQLDataSource) - asp.net

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

Related

How can I bind a gridview to datasource with dynamic WHERE clause?

I am using Visual Basic for ASP. NET
I know how to populate a gridview with data using only code behind, like this
Dim ds as new datasourse
Dim da as new dataadaptor
Dim con as new SqlConnection
Dim cmd as new SqlCommand
...
Cmd = "select ticketID, problem_text from problems where support_engineer = " & Session("Logged_in_user_id")
...
Gridview1.Datasource = ds
Gridview1.Datasources. DataBind
And that works fines, but my question is: how can i drag and drop a gridview control, and using only the wizard to populate the gridview in design time, how can i define the SELECT statement to only select rows that are related to the logged in user id? See the sql statement above, it uses a session variable that i create in Page_Load event, but how can i use the same logic in design mode? (i don't want to modify the datasource control in code behind)
I looked in youtube and google, and this sites, but all results are simply showing me how to populate the gridview with all rows or with a static condition, not a dynamic one like the one i demonestrated.
Any help is highly appreciated
You could try replacing the form tag in the aspx file
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT ticketID, problem_text FROM Tabs WHERE (support_engineer = #Param1)">
<SelectParameters>
<asp:SessionParameter Name="Param1" SessionField="Logged_in_user_id" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True"
DataSourceID="SqlDataSource1">
</asp:GridView>
</div>
</form>
I found out the proper way of binding the gridview to a dynamic session variable, without involving code behind:. Simply use the property <SessionParameter> inside the <SelectParameter>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT ticketID, problem_text FROM problems
WHERE (support_engineer = #eng_id)
<SelectParameters>
<asp:SessionParameter
Name="eng_id"
SessionField="LoggedInUser"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True"
DataSourceID="SqlDataSource1">
</asp:GridView>

change text on a hyperlink in a datalist

I'm trying to bind a column from a SQL code that i have written to all hyperlinks in a datalist. This should be really simple but I'm getting the error
DataBinding: 'System.Data.Common.DataRecordInternal' does not contain
a property with the name 'NumberOfComments'.
Well I'm pretty sure the column exist but in this case it's created by a function maybe that has something to do with it. When I run the SQL code i get the values I should.
The hyperlink
<asp:HyperLink ID="lnkComment" runat="server"
NavigateUrl='<%# Eval("ID", "~/Default.aspx?ID={0}") %>'
Text='<%# Eval("NumberOfComments") %>'></asp:HyperLink>
The SQLDataSource
<asp:SqlDataSource ID="sdsNews" runat="server"
ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString %>" SelectCommand="SELECT News.ID, News.Topic, News.Text, News.PostTime, aspnet_Users.UserName, "NumberOfComments" = dbo.fnNumberOfCommentOnNews(News.ID)
FROM News INNER JOIN
aspnet_Users ON News.UserId = aspnet_Users.UserId
WHERE (News.ID = ISNULL(#ID, News.ID))
ORDER BY News.PostTime DESC ">
<SelectParameters>
<asp:QueryStringParameter DbType="Guid" Name="ID" QueryStringField="ID" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
Why do you have """ surrounding NumberOfComments FieldName?
Try pasting the select command into SSMS (SQL Server Mgmt studio) and you should most definitely get an incorrect syntax error. If you drop those quot html code you will still be able to reference and bind to that column.

Passing a variable to a dynamic dropdownlist

I have 2 dropdownlists, one is State and the second is City. I am trying to create it so, when a user clicks the State, the second dropdownlist is populated with City names from a datatable.
Here is the code
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<%--<cc2:CascadingDropDown ID="CascadingDropDown1" runat="server"> </cc2:CascadingDropDown>--%>
<h1>Live Event Search Engine</h1><br />
State: <asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="ST_Code" DataValueField="ST_Code" /><asp:SqlDataSource
ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbConnection %>"
SelectCommand="SELECT [ST_Code] FROM [State]">
</asp:SqlDataSource>
City: <asp:DropDownList ID="ddlCity" runat="server" DataSourceID="SqlDataSource2" DataTextField="RS_City" DataValueField="RS_City" /><asp:SqlDataSource
ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:dbConnection %>"
SelectCommand="web_PublicProgramListbyState" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="State" SessionField="ST_Code" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</asp:Content>
and the code behind is
Public Sub ddlState_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlState.SelectedIndexChanged
Me.ddlCity.Items.Clear()
Dim da As New SqlDataAdapter("web_PublicProgramListbyState", New SqlConnection(ConfigurationManager.AppSettings("dbConnection")))
Dim ds As New DataSet
da.Fill(ds, "#State")
da.Dispose()
Me.ddlCity.DataSource = ds.Tables("Products")
Me.ddlCity.DataTextField = "ProductName"
Me.ddlCity.DataValueField = "ProductID"
Me.ddlCity.DataBind()
End Sub
End Class
Looks like you are trying to bring a dataset into this when you already have a SqlDataSource defined. Just modify the parameters of the SqlDataSource and re-bind:
Public Sub ddlState_SelectedIndexChanged(...)
SqlDataSource2.SelectParameters.Clear()
SqlDataSource2.SelectParameters.Add(New Parameter("#State", DbType.String, ddlState.SelectedValue))
ddlCity.DataBind()
End Sub
Edit: Or you can use a ControlParameter referencing ddlState.SelectedValue in SqlDataSource2.SelectParameters as mentioned in another answer. Only trick there is you have to manage your default values carefully so ddlCity only binds when you want it to.
I would change it to a control param and just call the databind. No need to do the fill yourself.
<asp:ControlParameter Name="State" ControlID="ddlState" Type="String" />
and then in the select event just call:
Me.ddlCity.DataBind()
Or if you want to remove the codebehind all together put it in an update panel with a trigger.
I don't see where the ddlState_SelectedIndexChanged event writes the session variable. This is required.

execute stored procedure using sqldatasource and get return value in vb.net

How can I execute a stored procedure using sqldatasource and get the return value in vb.net.
Thanks,
Terri
The method you are looking for is DataBind. Call it using mySqlDataSource.DataBind()
<asp:SqlDataSource
ID="sds2"
runat="server"
ConnectionString="..."
SelectCommand="spTest"
SelectCommandType="StoredProcedure"
>
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" PropertyName="Text"
Name="ParamName" Type="Int32" DefaultValue="0" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="gv" runat="server" DataSourceID="sds2"></asp:GridView>
The stored procedure is executed when you call DataBind. The DataBind method is called automatically if the DataSourceID property of the GridView control refers to a valid data source control.
You need to use a SqlConnection with a SqlCommand, like this:
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand("StoredProcedureName", connection)) {
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("SomeParam", someValue);
object result = command.ExecuteScalar();
}
If you already have the SP returning a value then you have to grab the value in the corresponding event for the data source. AKA - Inserted, Selected, etc...
Here's a couple links illustrating the point.
http://fredrik.nsquared2.com/viewpost.aspx?PostID=162
http://www.velocityreviews.com/forums/t86158-re-how-to-retrieve-an-output-parameter-using-sqldatasource-control.html
<asp:SqlDataSource ID="ADSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ADConnection %>"
SelectCommand="GetProfile" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="InputTextBox" Name="Host" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
GetProfile is the stored proc name and Host is parameter name, which is retreived from a texbox called InputTextBox

Change the property "DefaultValue" of the asp.net "ControlParameter" control with javascript

I already have an idea on how to do this, but I realized that the control "ControlParameter" did not have an "Id" property (which is needed for the JS). Is there a different way to use JavaScript to change the "DefaultValue" property without the need of using the "Id" property?
Here is the JavaScript and asp.net code that I have been working with:
JavaScript:
function ChangePropertyValue(propertyName, newpropertyValue) {
var ControlParameter = document.getElementById(propertyName)
ControlParameter.DefaultValue = newpropertyValue
}
asp.net:
<asp:Button ID="btntest" runat="server" Text="try" OnClick="ChangePropertyValue(??, 17)"/>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString1 %>"
SelectCommand="SELECT [Id], [ContentTitle], [Content] FROM [Table1] WHERE ([Id] = #Id)">
<SelectParameters>
<asp:ControlParameter ControlID="ListView1" DefaultValue="16" Name="Id"
PropertyName="SelectedValue" Type="Int32"/>
</SelectParameters>
</asp:SqlDataSource>
You can't access a ControlParameter client side. ControlParameters are used to bind the value of a Control property server side, they are not rendered to the client. You can, however, set the Default value of the ControlParameter programmatically in your Code Behind.
SqlDataSource1.SelectParameters["id"].DefaultValue = "value";

Resources