How to clear exisiting dropdownlist items when its content changes? - asp.net

ddl2 populates based on ddl1 selected value successfully.
My issue is the data that is already present in ddl2 does not clear before appending the new data so ddl2 content just continues to grow every time ddl1 is changed.
<asp:DropDownList ID="ddl1" RunAt="Server" DataSourceID="sql1" DataValueField="ID1" DataTextField="Name2" AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Text="ALL" Selected="True" Value="0"/>
</asp:DropDownList>
<asp:DropDownList ID="ddl2" RunAt="Server" DataSourceID="sql2" DataValueField="ID2" DataTextField="Name2" AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Text="ALL" Selected="True" Value="0"/>
</asp:DropDownList>
<asp:SqlDataSource ID="sql1" RunAt="Server" SelectCommand="sp1" SelectCommandType="StoredProcedure"/>
<asp:SqlDataSource ID="sql2" RunAt="Server" SelectCommand="sp2" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Type="Int32" Name="ID1" ControlID="ddl1" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>
I have tried re-databinding in code behind on selected index change and also items.clear with little success.
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
ddl2.Items.Clear()
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
QUESTION
How to get items present in an asp:dropdownlist to clear before new values are populated when the dropdownlists content is dependent on another dropdownlists selected value?
Please post any code in VB

Using ddl.Items.Clear() will clear the dropdownlist however you must be sure that your dropdownlist is not set to:
AppendDataBoundItems="True"
This option will cause the rebound data to be appended to the existing list which will NOT be cleared prior to binding.
SOLUTION
Add AppendDataBoundItems="False" to your dropdownlist.
Now when data is rebound it will automatically clear all existing data beforehand.
Protected Sub ddl1_SelectedIndexChanged(sender As Object, e As EventArgs)
ddl2.DataSource = sql2
ddl2.DataBind()
End Sub
NOTE: This may not be suitable in all situations as appenddatbound items can cause your dropdown to append its own data on each change of the list.
TOP TIP
Still want a default list item adding to your dropdown but need to rebind data?
Use AppendDataBoundItems="False" to prevent duplication data on postback and then directly after binding your dropdownlist insert a new default list item.
ddl.Items.Insert(0, New ListItem("Select ...", ""))

You should clear out your listbbox prior to binding:
Me.ddl2.Items.Clear()
' now set datasource and bind

Please use the following
ddlCity.Items.Clear();

Just 2 simple steps to solve your issue
First of all check AppendDataBoundItems property and make it assign false
Secondly clear all the items using property .clear()
{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}

just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal
e As EventArgs)
//ddl2.Items.Clear()
ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub
and it worked just fine

Related

How to set initial value as Select in the dropdown of asp.net page that is databound with sql statement

I am binding a dropdown for location with a select statment
Select location_id, location_name,businessid from inventory.tbl_location order by location_name
I want to put the first element as 'Select location'. Right now I am getting all locations. How to set initial value as Select in the dropdown of asp.net page that is databound with sql statement?
In the aspx page :
<asp:DropDownList ID="ddlAllLocations" runat="server" DataSourceID="SqlDataSourceBusinessLocations"
DataTextField="Location_Name" DataValueField="Location_ID" AutoPostBack="True">
</asp:DropDownList>
And
<asp:SqlDataSource ID="SqlDataSourceBusinessLocations" runat="server" ConnectionString="<xxxxxx>"
ProviderName="<%$ zzzzz %>" SelectCommand="Select location_id, location_name,businessid from inventory.tbl_location order by location_name" FilterExpression="businessid in ({0})">
<FilterParameters>
<asp:SessionParameter DefaultValue="0" Name="BUID" SessionField="BusinessUnitIDs" />
</FilterParameters>
</asp:SqlDataSource>
I added the code as suggested in the page_load event, here is another problem, everytime it is adding select location to the list items
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack() Then
lblError.Text = ""
ddlAllLocations.Items.Insert(0, New ListItem("Select location"))
End If
End Sub
Try this:
<asp:DropDownList ID="ddlAllLocations" runat="server"
DataSourceID="SqlDataSourceBusinessLocations"
DataTextField="Location_Name"
DataValueField="Location_ID"
AutoPostBack="True"
AppendDataBoundItems="True">
<asp:ListItem value="" selected="True">
Select
</asp:ListItem>
</asp:DropDownList>
Don't forget the AppendDataBoundItems attribute. Be careful using this in an update panel: each update will re-append all the items and you'll end up with duplicates. In that case, you might be able to fix it by disabling ViewState for the control.
Not sure how you do the databinding but I hope you're doing it in code-behind...
In that case it's pretty straighforward:
mydroplist.DataSource = someSource;
mydroplist.DataBind();
mydroplist.Items.Insert(0, new ListItem("Select location"));
edit based on your edit:
it's not a good idea to have SQL in your UI.. That's a very bad design. Do some research on proper programming architectures, how to separate layers etc. Then you will do the databinding in code-behind and my sample will help you.
If you insist on using your way of doing things, you can simply wire up the event when the dropdownlist is databound and add this piece of code (except the binding part of course)

Double Databinding Cascading DropDownList to two SqlDataSources in a FormView

I have two cascading dropdown lists I'm attempting to bind to two separate SqlDataSources each.
These dropdownlists exist in a FormView's EditItemTemplate. Inside the EditItemTemplate two sqldatasource controls exist that populate the department and the jobname. The DeptID and the JobID are the primary keys in those tables. This creates the "cascading effect" between departments and jobs. When a department is selected, only the jobs associated with that department appear.
This piece is working properly.
<asp:FormView ID="frmProfile" runat="server" DataSourceID="sqlDSProfile"
DataKeyNames="EUID" style="margin-top: 0px">
<EditItemTemplate>
<asp:DropDownList ID="ddlDepartments" runat="server" Width="135px"
DataSourceID="sqlDSDepartments"
DataTextField="Department"
DataValueField="DeptID" AutoPostBack="True"
SelectedValue='<%# Bind("CurrentDeptID") %>'
AppendDataBoundItems="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlJobNames" runat="server" Width="185px"
DataSourceID="sqlDSJobs" DataTextField="JobName" DataValueField="JobID"
SelectedValue='<%# Bind("CurrentJobID") %>'
AppendDataBoundItems="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDSDepartments" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblDepartments.DeptID,
tblDepartments.Department
FROM tblDepartments" />
<asp:SqlDataSource ID="sqlDSJobs" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblJobs.JobID, tblJobs.JobName FROM tblJobs
INNER JOIN tblDeptsJobs ON tblDeptsJobs.JobID = tblJobs.JobID
WHERE tblDeptsJobs.DeptID = #DeptID" >
<SelectParameters>
<asp:ControlParameter ControlID="ddlDepartments" Name="DeptID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
Outside the formview the SqlDataSource exists that binds all of the information to the Employee table in an update statement. I'm leaving all of the other information in this SqlDataSource even though it's been omitted from the FormView above.
<asp:SqlDataSource ID="sqlDSProfile" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblEmployee.EUID,
tblEmployee.DateHired,
tblEmployee.LastName,
tblEmployee.HiredLastName,
tblEmployee.FirstName,
tblEmployee.Role,
tblEmployee.JobGrade,
tblEmployee.CurrentDeptID,
tblDepartments.Department,
tblDepartments.DeptID,
tblEmployee.CurrentJobID,
tblJobs.JobName,
tblJobs.JobID,
tblEmployee.CurrentShift,
tblEmployee.JobDate,
tblEmployee.IsDisplaced,
tblEmployee.EligibilityDate
FROM tblEmployee
LEFT OUTER JOIN tblDepartments ON tblEmployee.CurrentDeptID = tblDepartments.DeptID
EFT OUTER JOIN tblJobs ON tblEmployee.CurrentJobID = tblJobs.JobID
WHERE (tblEmployee.EUID = #EUID)"
UpdateCommand="UPDATE [tblEmployee]
SET [tblEmployee].[DateHired] = #DateHired,
[tblEmployee].[LastName] = #LastName,
[tblEmployee].[HiredLastName] = #HiredLastName,
[tblEmployee].[FirstName] = #FirstName,
[tblEmployee].[Role] = #Role,
[tblEmployee].[JobGrade] = #JobGrade,
[tblEmployee].[CurrentDeptID] = #CurrentDeptID,
[tblEmployee].[CurrentJobID] = #CurrentJobID,
[tblEmployee].[CurrentShift] = #CurrentShift,
[tblEmployee].[JobDate] = #JobDate,
[tblEmployee].[IsDisplaced] = #IsDisplaced,
[tblEmployee].[EligibilityDate] = #EligibilityDate
WHERE [tblEmployee].[EUID] = #EUID"
ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:SessionParameter Name="EUID" SessionField="sProfileEUID" DbType="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="DateHired" DbType="Date" />
<asp:Parameter Name="LastName" DbType="String" />
<asp:Parameter Name="HiredLastName" DbType="String" />
<asp:Parameter Name="FirstName" DbType="String" />
<asp:Parameter Name="Role" DbType="String" />
<asp:Parameter Name="JobGrade" DbType="Byte" />
<asp:Parameter Name="CurrentDeptID" DbType="Int32" />
<asp:Parameter Name="CurrentJobID" DbType="Int32" />
<asp:Parameter Name="CurrentShift" DbType="Int32" />
<asp:Parameter Name="JobDate" DbType="Date" />
<asp:Parameter Name="IsDisplaced" DbType="Boolean"/>
<asp:Parameter Name="EligibilityDate" DbType="Date"/>
<asp:SessionParameter Name="EUID" SessionField="sProfileEUID" DbType="String" />
</UpdateParameters>
</asp:SqlDataSource>
The only pieces I can't figure out how to bind are the Departments and the Jobs. Everything else is working. I've tried using the following code in the DropDownList controls...
SelectedValue='<%# Bind("CurrentDeptID") %>'
SelectedValue='<%# Bind("CurrentJobID") %>'
...but these result in errors.
Summary
When the user clicks edit, I need the values in the two dropdownboxes to pull their selectedvalue from the main sqlDSProfile data source, but I need them to be updatable. I've gotten it to the point where I can update and bind the job that an associate belongs to, but because the dropdownlists cascade, when I attempt to change the department the AutoPostBack breaks the binding between sqlDSProfile - CurrentJobID and ddlJobs.
Update
I added tblEmployee.CurrentDeptID and tblEmployee.CurrentJobID to the select statement, and added Bind() statements to the DropDownList controls.
SelectedValue='<%# Bind("CurrentDeptID") %>'
SelectedValue='<%# Bind("CurrentJobID") %>'
The two DropDownLists are now populated with accurate information pulled from the Employee table, showing the department and job that the employee belongs to.
The two DropDownLists are also populated by the two SqlDataSources inside the FormView, giving me options for changing the department and changing the job.
When I change the Job, it works and the employees job is updated.
When I change the Department, it breaks saying DataBinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
Close to Done
I removed the data binding from ddlJobs and coded that in the background.
Protected Sub frmProfile_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles frmProfile.ItemUpdating
If frmProfile.CurrentMode = FormViewMode.Edit Then
e.NewValues("CurrentJobID") = DirectCast(DirectCast(sender, FormView).FindControl("ddlJobs"), DropDownList).SelectedValue
End If
End Sub
The only piece that's left is building the code for when the ddlDepartments changes.
pseudocode...
' If Item exists in ddlJobs Then
' select item (CurrentJobID)
' else
' select index 0 and make them pick something new
' end if
So Close!
Updated Again
This is the code I've developed to loosely bind this. In the page_load I'm trying to pull the contents of CurrentJobID from sqlDSProfile and check to see if that value exists in ddlJobs. If it does I want to set ddlJobs.SelectedValue = to that CurrentJobID. If it doesn't I want to set the selectedindex to 0 which is a message saying "pick one" or something.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If frmProfile.CurrentMode = FormViewMode.Edit Then
' Need to determine if the CurrentJobID returned in the select statement
' exists in the ddlJobs dropdownlist. If it does, set that to the
' selectedvalue, if not set it to 0 so the user can select a new job.
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim dvProfile As DataView = sqlDSProfile.Select(DataSourceSelectArguments.Empty)
Dim drvProfile As DataRowView = dvProfile(0)
If ddlJobs.Items.FindByValue(drvProfile("CurrentJobID")) Is DBNull.Value Then
ddlJobs.SelectedIndex = 0
Else
ddlJobs.SelectedValue = drvProfile("CurrentJobID")
End If
End If
End Sub
Its returning a null reference exception on the line where I'm checking for dbnull.value
I had a similar issue and found a very simple resolution, (and in c#). Imagine a database with a table Questions, related to category and subcategory tables (which are also related and constrained). When trying to update existing records asp throws an error. This is the solution that I worked out thanks to the information above from Lucretius et al.
Only databind the parent dropdownlist
Find a way to insert the child dropdown selected value on the update event of the datasource.
As:
protected void odseditquestion_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
//dynamically assign value from ddlsubcategory to odseditquestion on updating event
//you really should not have to do this
DropDownList ddlsubcategory = (DropDownList)fveditquestion.FindControl("ddlsubcategory");
e.InputParameters["subcatid"] = (ddlsubcategory.SelectedValue);
}
It works on my application. Hope it helps somebody, this one cost me half a day, such is asp!!
The problem can be if tlbEmployee columns in the SqlDSProfile in the update statement and field names used by your controls do not match. Other procedures you've followed are right.
SqlDataSource control expects field names it updates to be similar
with those bound to the controls(fields) inside the DataBound control.
The Solution can be: change all the update Parameters to ControlParameters referencing the right control for each one
Update: Wait, I think the problem is your select statement of the SqlDSProfile should contain: CurrentDeptID and CurrentJobID. Try it:
<asp:SqlDataSource ID="sqlDSProfile" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblEmployee.EUID,
tblEmployee.DateHired,
tblEmployee.LastName,
tblEmployee.HiredLastName,
tblEmployee.FirstName,
tblEmployee.Role,
tblEmployee.JobGrade,
tblDepartments.Department,
tblJobs.JobName,
tblEmployee.CurrentShift,
tblEmployee.JobDate,
tblEmployee.IsDisplaced,
tblEmployee.EligibilityDate
tblEmployee.CurrentDeptID,
tblEmployee.CurrentJobID
FROM tblEmployee
Advice: Test your code portion by portion.
Try the code without the dropdownlist, Test separately
Add the one drop downlist
Use select * from ... in select queries
Avoid ajax when testing
If you make it
Add portions of code portion after portion
at last use the partial updating (ajax)
I have a working solution now, thanks in part to Nuux and a bunch of online research. The tip about the join statement wasn't relevant, but the tip about including "CurrentJobID" and "CurrentDeptID" in my select query was spot on.
In addition to that I had to rework the controls a little. The two cascading dropdownlists are below. The ddlJobs dropdown list behaves like a normal databound control, but it doesn't have the Bind("CurrentJobID") statement I was trying in my original post.
<asp:DropDownList ID="ddlDepartments" runat="server" Width="185px"
DataSourceID="sqlDSDepartments"
DataTextField="Department"
DataValueField="DeptID"
SelectedValue='<%# Bind("CurrentDeptID") %>'
AppendDataBoundItems="true"
AutoPostBack="True" >
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
<asp:DropDownList ID="ddlJobs" runat="server" Width="185px"
DataSourceID="sqlDSJobs"
DataTextField="JobName"
DataValueField="JobID"
AppendDataBoundItems="true"
OnDataBinding="ddlJobs_DataBinding" />
The only thing the custom routine "ddlJobs_DataBinding" is doing is adding "--Select One--" as index 0 in the ddlJobs dropdown. I tried this in several places, like page_load, and the databound event of the formview with no success.
Protected Sub ddlJobs_DataBinding(sender As Object, e As System.EventArgs)
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim liSelectOne As New ListItem("--Select One--", 0)
ddlJobs.Items.Clear()
ddlJobs.Items.Insert(0, liSelectOne)
End Sub
The databound event of the formview frmProfile_DataBound event does do some work though. When the user clicks "edit" on the formview to enter editing mode this ensures that the dropdownlist ddlJobs has the correct job selected by default for the profile in question. If the user hasn't been assigned to a job then it defaults to selectedindex 0 which is "--Select One--" set in custom databinding event just above.
Protected Sub frmProfile_DataBound(sender As Object, e As System.EventArgs) Handles frmProfile.DataBound
If frmProfile.CurrentMode = FormViewMode.Edit Then
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim dvProfile As DataView = sqlDSProfile.Select(DataSourceSelectArguments.Empty)
Dim drProfile As DataRow = dvProfile.Table.Rows(0)
If drProfile("CurrentJobID").ToString() = "" Then
ddlJobs.SelectedIndex = 0
Else
ddlJobs.SelectedValue = drProfile("CurrentJobID").ToString()
End If
End If
End Sub
Finally, if the user selects a new job from ddlJobs, that value has to be fed to the database, which the ItemUpdating event of the formview handles.
Protected Sub frmProfile_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles frmProfile.ItemUpdating
If frmProfile.CurrentMode = FormViewMode.Edit Then
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
e.NewValues("CurrentJobID") = ddlJobs.SelectedValue
End If
End Sub
Done!

access selectcommand using codebehind

How can I change my selecommand, and keep it through the remainder of the page (when using pagination, sorting)?
I have a page of checkboxes:
<input type="checkbox" name="checkbox_1" />
<input type="checkbox" name="checkbox_2" />
<input type="checkbox" name="checkbox_3" />
<asp:Button runat="server" Id="CustomButton" text="Create Report" PostBackUrl="report.aspx?"/>
Then on report.aspx I want to generate a standard listview based on the selections in the checkbox.
<asp:ListView runat="server" ID="ReportListView" DataSourceID="ReportListViewSDS">
<LayoutTemplate runat="server">
...<asp:PlaceHolder runat="server" ID="itemPlaceHolder" />...
</LayoutTemplate>
<ItemTemplate>
...
</ItemTemplate>
</asp:ListView>
I want to be able to sort and paginate that listview. This is an idea of what i want in the code behind:
Protected Sub ReportListView_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)
' What's the correct way to reference the listview?
' When I use the below code i get "ReportListView is not declared...."
' ReportListView.SqlCommand = "SELECT " & checkbox1 & ", " & checkbox2 & " WHERE..."
End Sub
I'm not sure if I'm even going in the right direction with this, any help is appreciated. Will the changes i make to the sql command in the PreRender function hold when I have applied pagination or sorting to the listview?
If I understand your question correctly, you want to open a new page and use the prior page's values in the select statement for the ListView's SqlDataSource on the new page, correct?
First, a few observations:
In your first page, you appear to be intending to call the second page with a query string (PostBackUrl="report.aspx?), but you don't appear to set the query string.
Your PreRender event for the ListView control has the wrong signature. It only takes one argument, EventArgs:
Protected Sub ReportListView_PreRender(ByVal e As EventArgs)
Your ListView appears to be using a SqlDataSource as it's binding source (DataSource="ReportListViewSDS"). More about that below.
There is no SqlCommand property or method for the ListView control.
Since you're binding the ListView to a SqlDataSource, it'd be simplest to set the Select command and the parameters in the markup, like this:
<asp:SqlDataSource ID="ReportListViewSDS" runat="server"
SelectCommand="SELECT checkbox1, checkbox2, checkbox3 FROM <table> WHERE checkbox1 = #parm1 AND checkbox2 = #parm2 AND checkbox3 = #parm3">
<SelectParameters>
<asp:FormParameter FormField="checkbox_1" Name="parm1" />
<asp:FormParameter FormField="checkbox_2" Name="parm2" />
<asp:FormParameter FormField="checkbox_3" Name="parm3" />
</SelectParameters>
</asp:SqlDataSource>
Replace <table> in the SelectCommand with the name of your table. You can adjust the names of the columns you're selecting, as well as the parameters you're using, as desired. I simply used 3 checkboxes as that's what you had in the code you posted.
Also note, NO VALIDATION of the parameters will be done by the SqlDataSource, so if you want to prevent SQL Injection attacks and other security risks, you'll want to do validation in the Selecting event of the SqlDataSource.
More information can be found here:
SqlDataSource Class
FormParameter Class
Actually this was much easier than I thought. Sorry, just a newbie mistake i guess. i ended up simply doing:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim SqlCommand As String
' create the sql command using the Request.Form vars i wanted.
' ...
' Run the sql command, I can access the listview directly, just like a global variable:
ReportListView.SelectCommand = SqlCommand
ReportListView.DataBind()
End Sub
And that seemed to do it. Actually very easy.

Why won't my UpdatePanel update my Listbox as I expect on button click?

I have a form with a dropdownlist, two buttons, and two Listboxes inside an UpdatePanel. The Dropdownlist, and listboxes are all bound to SqlDatasources. The dropdownlist allows you to choose your department.
The first listbox shows a list of Jobs associated with what you've selected from the department.
The second listbox shows an inverse list of those items. (Jobs in the database that are not associated with your department)
When an item is removed from the 1st listbox, it should show up in the 2nd listbox. When an item is removed from the 2nd listbox, it should show up in the 1st listbox.
This functionality allows you to add and remove jobs from your department
The are two buttons on the page function as Add and Remove buttons. Everything is working except the Listboxes will not reliably update. The Data itself is updated in the database, and if I refresh (F5) it will show correctly.
<asp:ScriptManager ID="smgrDeptsJobs" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="uPanelDeptsJobs" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlDepartments" runat="server"
DataSourceID="sqldsDepartments" DataTextField="Department"
DataValueField="DeptID" Width="150px" AutoPostBack="True">
</asp:DropDownList>
<asp:ListBox ID="lstJobsIn" runat="server" DataSourceID="sqldsJobsIn"
DataTextField="JobName" DataValueField="JobID" height="156px"
width="220px">
</asp:ListBox>
<asp:Button ID="btnAddJob" runat="server" Text="<<" Width="70px"
CausesValidation="False" />
<asp:Button ID="btnRemoveJob" runat="server" Text=">>" Width="70px"
CausesValidation="False" />
<asp:ListBox ID="lstJobsOut" runat="server" DataSourceID="sqldsJobsOut"
DataTextField="JobName" DataValueField="JobID" height="156px"
width="220px">
</asp:ListBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlDepartments"
EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="btnAddJob" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnRemoveJob" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
The code for the two button click events is below:
Protected Sub btnAddJob_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddJob.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdInsert As SqlCommand = sqlJobsDB.CreateCommand()
sqlJobsDB.Open()
sqlCmdInsert.CommandText = _
"INSERT INTO tblDeptsJobs (DeptID, JobID) VALUES " + _
"(#DeptID, #JobID)"
' Declare the data types for the parameters
sqlCmdInsert.Parameters.Add("#DeptID", SqlDbType.TinyInt)
sqlCmdInsert.Parameters.Add("#JobID", SqlDbType.TinyInt)
' Assign the parameters values from the form
sqlCmdInsert.Parameters("#DeptID").Value = ddlDepartments.SelectedValue
sqlCmdInsert.Parameters("#JobID").Value = lstJobsOut.SelectedValue
' Execute the insert Statement
sqlCmdInsert.ExecuteNonQuery()
sqlJobsDB.Close()
End Sub
Protected Sub btnRemoveJob_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemoveJob.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdDelete As SqlCommand = sqlJobsDB.CreateCommand()
sqlJobsDB.Open()
sqlCmdDelete.CommandText = _
"DELETE FROM tblDeptsJobs WHERE tblDeptsJobs.DeptID = #DeptID AND tblDeptsJobs.JobID = #JobID"
' Declare the data types for the parameters
sqlCmdDelete.Parameters.Add("#DeptID", SqlDbType.TinyInt)
sqlCmdDelete.Parameters.Add("#JobID", SqlDbType.TinyInt)
' Assign the parameters values from the form
sqlCmdDelete.Parameters("#DeptID").Value = ddlDepartments.SelectedValue
sqlCmdDelete.Parameters("#JobID").Value = lstJobsIn.SelectedValue
' Execute the insert Statement
sqlCmdDelete.ExecuteNonQuery()
sqlJobsDB.Close()
End Sub
It feels like when I add or remove a job, the listbox that I last selected an item in, is the one that doesn't update.
I also can't get the dropdownlist to update the listboxes without setting autopostback on the dropdownlist to True.
The ugly Band-Aid fix I've come up with is using the listbox.items.clear() method and then rebinding the data for each listbox.
Basically what is happening is that you update your database but never rebind your controls. I'm not sure exactly what you will have to put into your click handlers to make this work (because I have never used the SQL datasource controls before), but it should look something like this:
Protected Sub btnAddJob_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddJob.Click
Dim sqlJobsDB As New SqlConnection(ConfigurationManager.ConnectionStrings("JobsDB").ConnectionString)
Dim sqlCmdInsert As SqlCommand = sqlJobsDB.CreateCommand()
sqlJobsDB.Open()
sqlCmdInsert.CommandText = _
"INSERT INTO tblDeptsJobs (DeptID, JobID) VALUES " + _
"(#DeptID, #JobID)"
' Declare the data types for the parameters
sqlCmdInsert.Parameters.Add("#DeptID", SqlDbType.TinyInt)
sqlCmdInsert.Parameters.Add("#JobID", SqlDbType.TinyInt)
' Assign the parameters values from the form
sqlCmdInsert.Parameters("#DeptID").Value = ddlDepartments.SelectedValue
sqlCmdInsert.Parameters("#JobID").Value = lstJobsOut.SelectedValue
' Execute the insert Statement
sqlCmdInsert.ExecuteNonQuery()
sqlJobsDB.Close()
//may need to do explicit call to DB to get data here
//after you have the data, rebind
lstJobsIn.DataBind();
lstJobsOut.DataBind();
End Sub
That's roughly what it will look like. I would be interested to see what exactly you do to solve your problem.
Just set dropdownlist autopostback to true, remove all triggers and set ChildrenAsTriggers="true" on the updatepanel.

Databound drop down list - initial value

How do I set the initial value of a databound drop down list in ASP.NET?
For instance, I want the values, but the first value to display should be -- Select One ---, with a null value.
I think what you want to do is this:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.
If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator>
I know this is old, but a combination of these ideas leads to a very elegant solution:
Keep all the default property settings for the DropDownList (AppendDataBoundItems=false, Items empty). Then handle the DataBound event like this:
protected void dropdown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
list.Items.Insert(0, "--Select One--");
}
The icing on the cake is that this one handler can be shared by any number of DropDownList objects, or even put into a general-purpose utility library for all your projects.
What I do is set the text property of the drop down list AFTER I databind it. Something like this:
protected void LoadPersonComboBox()
{
var p = new PeopleBLL();
rcmbboxEditPerson.DataSource = p.GetPeople();
rcmbboxEditPerson.DataBind();
rcmbboxEditPerson.Text = "Please select an existing person to edit...";
}
This makes the initial visible value of this dropdown show up, but not actually be a part of the drop down, nor is it a selectable.
I know this already has a chosen answer - but I wanted to toss in my two cents.
I have a databound dropdown list:
<asp:DropDownList
id="country"
runat="server"
CssClass="selectOne"
DataSourceID="country_code"
DataTextField="Name"
DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource
id="country_code"
runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>
In the codebehind, I have this - (which selects United States by default):
if (this.IsPostBack)
{
//handle posted data
}
else
{
country.SelectedValue = "US";
}
The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)
To select a value from the dropdown use the index like this:
if we have the
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
you would use :
DropDownList1.Items[DropDownList1.SelectedIndex].Value
this would return the value for the selected index.
hi friend in this case you can use the
AppendDataBound="true"
and after this use the list item.
for e.g.:
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
but the problem in this is after second time select data are append with old data.
Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.
If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though
Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DepartmentDropDownList.DataBound
If Not Page.IsPostBack Then
DepartmentDropDownList.SelectedValue = "somevalue"
End If
End Sub
dropdownlist.Items.Insert(0, new Listitem("--Select One--", "0");

Resources