How can I bind a gridview to datasource with dynamic WHERE clause? - asp.net

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>

Related

How to populate a dropdown list in asp.net from a DB table?

I want to populate a dropdown list with values from a table I created. I only want to populate the list with one of the fields- the languages in my table. I think I have connected to the data source correctly, but I don't know what I have to do to get the values into the list. I can enter my own values but I'd rather have this automated.
This is what I have so far, but I'm guessing there's more to it than just linking the list to the data source.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HBshareIndexConnectionString %>"
SelectCommand="SELECT * FROM [Web_Metrics] WHERE ([LCID] = #LCID)">
<SelectParameters>
<asp:QueryStringParameter Name="LCID" QueryStringField="LCID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="Label1" runat="server" Text="Select LCID: " ></asp:Label>
<asp:DropDownList ID="DropDownList1" Width="150px" runat="server" DataSourceID="SqlDataSource1" DataTextField="LCID" DataValueField="LCID">
<asp:ListItem>Select LCID...</asp:ListItem>
</asp:DropDownList>
Thanks for the help. I got the dropdown list populated now, but I was wondering how do I actually get the repeater I'm using to display the details of the LCID the person selects? I've seen people talking about page.isPostback but I don't know what that is or if it works with my current setup. I need to somehow get the LCID they selected and then refresh the page to show the details of that LCID. Does anyone have any ideas?
Your problem is that you're trying to define list items and a data source.
If you want to insert a "Select an item.." option, I would suggest prepending it to your resultset (getting it to always be first with a UNION and ORDER BY could be difficult depending on your fields) or inserting it after databinding in your code behind:
Modification to DropDownList1s attributes:
<asp:DropDownList ID="DropDownList1" Width="150px" runat="server" DataSourceID="SqlDataSource1" DataTextField="CountryName" DataValueField="LCID" OnDataBound="InsertChooseItem" />
C#:
protected void InsertChooseItem(object sender, EventArgs e)
{
ListItem selectOnePlease = new ListItem("Select LCID..", 0);
DropDownList1.Items.Insert(0, selectOnePlease);
}
VB:
Protected Sub InsertChooseItem(sender As Object, e As EventArgs)
Dim selectOnePlease As New ListItem("Select LCID..", 0)
DropDownList1.Items.Insert(0, selectOnePlease)
End Sub
You've specified the select parameter to be a query string, so the data in your DropDownList will only be populated when the URL resembles something like:
http://{Your server name}/Default.aspx?LCID=1
That doesn't make any sense though because the LCID column in your table should be unique, so although this will work there will only be one value in the drop down list.
I think what you want is to display all the languages from the database in the drop down, here's an example:
<asp:SqlDataSource ID="sqlDS" runat="server"
ConnectionString="<%$ ConnectionStrings:HBshareIndexConnectionString %>"
SelectCommand="SELECT LCID,Language FROM [Web_Metrics]">
</asp:SqlDataSource>
<asp:DropDownList ID="ddlLanguages" AppendDataBoundItems="true" Width="150px" runat="server" DataSourceID="sqlDS" DataTextField="Language" DataValueField="LCID">
<asp:ListItem>Select Language</asp:ListItem>
</asp:DropDownList>
Just a note, you should never display the ID to the client, it's totally meaningless to them, the ids are mostly used by developers in the background that's why in the drop down I set the:
DataTextField="Language" (This is the language name visible to the user)
DataValueField="LCID" (Not visible to the user, but useful for any additional processing in code behind)
AppendDataBoundItems="true" - this line of code will keep all the items you've manually added to the drop down, e.g "Select Language" and will append any data bound items e.g from a SQL table

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

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.

asp.net dropdownlist

I have two dropdownlists for a search, the 1st list is for the city and the second is for the area within the selected city. I would like to add a default value in the 2nd dropdownlist that will search ALL of the areas by default unless a specific area is selected from the list that contains the areaID for a specific search.
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="cityName" AutoPostBack="true" DataValueField="cityID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Cities]"></asp:SqlDataSource>
<asp:DropDownList ID="DropArea" runat="server" DataSourceID="SqlArea"
DataTextField="areaName" DataValueField="areaID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlArea" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [area] WHERE ([cityID] = #cityID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="0" Name="cityID"
PropertyName="SelectedValue" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Search" onclick="Button1_Click" />
Bind the second from code behind. Create a data table and insert the Select text at the begining and bind the datatable to the DDL.
DataTable dt =
DataRow dr = dt.NewRow()
dr["areaName"] = "All";
dr["SqlArea"] = "All";
tbldata.Rows.InsertAt(dr,0);
DropArea.DataSource = dt;
DropArea.DataBind();
You can try to add for second dropdownlist OnDataBound="DropArea_DataBound" event.
And use in code:
protected void DropArea_DataBound(object sender, EventArgs e)
{
DropArea.Items.Insert(0, new ListItem() {Value = "-1", Text = "ALL"});
}
And then when you handle click event, check:
var value = DropArea.SelectedItem.Value;
if(string.equals(value, '-1')
{
use your logic here
}
Hope it will help with your problem.
Best regards, Dima.
Chris,
I got the idea below from an answer HERE, but basically you want to modify your query to be in the form of the following:
Your Original:
SELECT * FROM [Cities]
Change To:
SELECT City FROM [Cities]
UNION ALL
SELECT 'ALL'
Old question, but you never found an answer.

Pull one record from the database and bind to an HTML tag

In ASP.NET, what is the definitive way to pull one record from the database and bind it and HTML tag? Brevity and style points count.
For brevity, you'll want to use the SqlDataSource.
<asp:SqlDataSource ID="sql" runat="server" ConnectionString='<%$ ConnectionStrings:MyConnectionString %>'
SelectCommandType="Text"
SelectCommand="select MyField FROM MyTable WHERE ID = #id"
>
<SelectParameters>
<asp:ControlParameter ControlID="txtUserName" PropertyName="Text" Name="id" />
</SelectParameters>
</asp:SqlDataSource>
<asp:BulletedList runat="server" DataTextField="MyField" DataSourceID="sql">
</asp:BulletedList>
It's not clear what you want but, detailsview control is designed for displaying only one record from data source.
DetailsView is a data-bound user
interface control that renders a
single record at a time from its
associated data source, optionally
providing paging buttons to navigate
between records.

Resources