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

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)

Related

How to clear exisiting dropdownlist items when its content changes?

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

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

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!

Duplicate items in dropdownlist!

Ok I really hope you guys can help me with this, I've spent the past 2 days trying to figure it out and I think I'm about to throw my computer out the window, so I thought I might as well ask here first:
I'm designing a web page with two dropdownlists, one for the Make of a car, the other for the Model, both bound to a database with separate SQLDataSources, and using a distinct statement. I add "All" at the top of both by setting appendDataBoundItems = true and adding items named all. Then when I fill the Make with a querystring all the model items get added twice (but only the databound items).
Here's my code:
<asp:DropDownList ID="DropDownMake" runat="server"
DataSourceID="SqlMakes" DataTextField="Make" DataValueField="Make"
AppendDataBoundItems="True" EnableViewState="False" AutoPostBack="True">
<asp:ListItem Selected="True" Value="All">All</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownModel" runat="server"
AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="SqlModels"
DataTextField="Model" DataValueField="Model" EnableViewState="False">
<asp:ListItem>All</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlMakes" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Make] FROM [Parts]">
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlModels" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [Model] FROM [Parts] WHERE ([Make] = #Make)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownMake" Name="Make"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
'And in the VB file:
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
DropDownMake.SelectedValue = Request.QueryString("Make")
DropDownModel.SelectedValue = Request.QueryString("Model")
End Sub
If I remove the line "DropDownMake.SelectedValue = Request.QueryString("Make")" it doesnt produce duplicates anymore. What is going on?? I swear I've spent more time developing entire iphone apps, if anyone helps figure this out I think I'm going to have to make an award for you.
Thank you!!
I think your databind method might be fired twice. Have you tried to set appendDataBoundItems=false and then attach an event handler for the OnDataBound event and insert your top item in the event handler instead?
protected void yourDdlControl_DataBound(object sender, EventArgs e)
{
if (yourDdlControl.Items.Count > 0)
{
yourDdlControl.Items.Insert(0, "All");
yourDdlControl.Items[0].Value = "";
yourDdlControl.SelectedIndex = 0;
}
}
}
Ok, so that is c# code, but you should be able to translate it :). Also, you can set the selected value in the DataBound instead based on the existence of your query parameters.
Put your code inside not postback i.e.
If Not Page.IsPostBack Then
DropDownMake.SelectedValue = Request.QueryString("Make")
DropDownModel.SelectedValue = Request.QueryString("Model")
End If

Using now() in a <asp:textbox>

Can anyone help. I am using a formview in VS 2005. I have different elements in my form databound to a database and I am performing an INSERT SQL statement. No problem. The problem is that I am trying to enter the current date into the SQL statement and I am having a problem.
I can add <%now()%> to the "Text" property of the asp:Textbox. But when I do, then I can't bind the textbox to a specific database column.
How do I do both????
I can do this:
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Initiate_Date") %>' ></asp:TextBox>
Or this:
<asp:TextBox ID="TextBox2" runat="server" Text='<%# now() %>' ></asp:TextBox>
But I don't know how to do both.
Leave it bound to Initiate_Date in the aspx but in your code behind set it to Now() when you need to....
Handle the ItemUpdating method of your formview. There you can cancel the event and write your own db handling code by getting the values from the formview, or you can just change the data item in the formview and inject your chages (and let the formview handle teh database)
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formview.itemupdating.aspx
I needed to get the now() value into the selectcommand of my sqldatasource. There was no need for a textbox.
This is what I ultimately did.
On the code behind I created a session variable and set Now() to the value.
> Protected Sub Page_Load(ByVal sender
> As Object, ByVal e As
> System.EventArgs) Handles Me.Load
> Dim RightNow As Date = Now()
> Dim RightNowShort As Date = RightNow.ToShortDateString
>
> Session("RightNow") = RightNowShort
> End Sub
On the aspx page I use the variable in a sessionparameter tag in the InsertParameters tag of my SqlDataSource.
<InsertParameters>
<asp:sessionparameter sessionfield="RightNow" type="String" name="RightNow" />
</InsertParameters>
Thanks.

Resources