Databound drop down list - initial value - asp.net

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");

Related

How to bind SelectedValue of DropdownList to DataSoruce when drop down is populated programmatically?

I have a GridView. When I go into edit mode on a row, I want one of the columns to be a dropdown. My first draft included this:
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<%# Eval("type_name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ctlItemType" runat="server" datasourceid="dsItemTypes"
DataTextField="name" DataValueField="id"
selectedvalue='<%# Bind("item_type_id") %>' />
</EditItemTemplate>
</asp:TemplateField>
I should clarify that my data source included "type_name" as the name of the type and "item_type_id" as the ID corresponding to that name. That worked great. Cool.
But I need to restrict the values appearing in the drop down depending on other data about the record. So okay, fine, I removed the datasourceid, and instead populated the dropdown with code:
Private Sub ItemsGridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Handles ItemsGridView.RowDataBound
If e.Row.RowState = DataControlRowState.Edit Then
Dim ctlItemType As DropDownList = e.Row.FindControl("ctlItemType")
Dim parent_id = ItemsGridView.DataKeys(e.Row.RowIndex).Values(1)
ctlItemType.DataSource = ItemTypeActions.List(parent_id)
ctlItemType.DataBind()
End If
End Sub
That blows up with a "SelectedValue not found" error, I presume because it's trying to set the selected value before I populate the values.
So I tried setting the SelectedValue in code also. After the DataBind above I added:
ctlItemType.SelectedValue = DataBinder.Eval(e.Row.DataItem, "item_type_id")
That displays fine when I go into edit mode, but when I click "Update", it blows up, because item_type_id doesn't get included in the list of parameters passed to the update function. Because it's not Bind'ed, it's just set with an Eval.
So how do I make this work? Is there a way to bind a control to a datasource with code? I could find anything like DataBinder.Eval that is equivalent to <%# bind("whatever") %>. Or ... what?

How do I set the Selected Value of a DropDownList inside an EditItemTemplate inside a DetailsView using the codebehind?

I have a Details View on my ASP.NET (VB) page which lists the details of a customer (their name, address, etc).
The 'Country' option is a drop down list, pulled from a database table. This all works fine when viewing the Details View and you can see what country they are in.
However, when I click the Edit button on the DetailsView, the drop down list then shows all the available countries in the db table correctly but it has no selected value, so instead of selecting their currently-set country, it just defaults to the top one in the list. This is wrong as it's not their currently-set value.
Using the codebehind (VB), how should I set the selected value of the dropdown list to be the country name that they currently have set? In the codebehind, I have already read their current country name in and stored it in a string variable called strCurrentCountryName
eg.
Response.Write "strCurrentCountryName: " & strCurrentCountryName
Will show:
strCurrentCountryName: United Kingdom
So I now need to match their strCurrentCountryName value with one of the country names in the drop down list and set this as the SelectedValue for them.
My code in front (which lists all the countries in the db):
<asp:TemplateField HeaderText="Country" SortExpression="address5">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSourcecountryList" runat="server" ConnectionString="<%$ ConnectionStrings:PDConnectionString %>"
ProviderName="<%$ ConnectionStrings:PDConnectionString.ProviderName %>"
SelectCommand="SELECT country_name_short, country_name_long FROM country_list WHERE deleted = 0 ORDER BY country_name_long">
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownListCountry" runat="server" CssClass="form-control"
DataSourceID="SqlDataSourcecountryList" DataTextField="country_name_long" DataValueField="country_name_short">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("address5") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
In the codebehind, I tried this (inside the Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load):
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
Which gives an error message of:
'DropDownListCountry' is not declared. It may be inaccessible due to its protection level
I tried using these two lines of code with the drop down list placed OUTSIDE of the EditItemTemplate and it works perfectly:
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
Sure enough, it does then correctly set their Selected Value to be the correct country.
In my codebehind (vb), do I need to somehow declare the DropDownListCountry first?
How do I make this work when placed inside the EditItemTemplate of my asp:TemplateField ?
Since the drop down is inside the template, it is not statically declared anywhere in the page's code, and so there is no way to reference it directly by just DropDownListCountry. Consider this - if that was possible, and you had a grid view template with these, drop down in which row would you be referencing?
So in reality this drop down gets assigned a different ID based on the container template it is in. So you need to find it inside the template on data binding time and then set the selected value the way you did:
Dim ddl As DropDownList = CType(detailsViewId.FindControl("DropDownListCountry"), DropDownList)
ddl.Items.FindByText(strCurrentCountryName).Selected = True
Important thing is to make sure that this code is run once drop down control was created. Most suitable place is right after data binding happend. To do so, subscribe to the DataBound event:
<asp:DropDownList ID="DropDownList1" runat="server" OnDataBound="DropDownList1_DataBound">
and run the code inside the event handler:
Protected Sub DropDownList1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
' Code above goes here
End Sub

Cant set and get value using dropdown list

This dropdown list is inside a gird view:
<asp:TemplateField HeaderText="Test">
<ItemTemplate>
<asp:DropDownList ID="Hello" runat="server" SelectedValue='<%# Eval("beta") %>'>
<asp:ListItem Value="" Text="-">-</asp:ListItem>
<asp:ListItem Value="0" Text="0">0</asp:ListItem>
<asp:ListItem Value="1" Text="1">1</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Every time it has to load the page containing this gridview I get exception:
{"'beta' has a SelectedValue which is invalid because it does not exist in the list of items.\r\nParameter name: value"}
The value of beta is null, however,
<asp:ListItem Value="null" Text="null">null</asp:ListItem>
Doesnt work... Note beta comes from database as the next possible values: null, 0 or 1 .Also tried getting the values from another dropdown list but doesnt work, i tried this:
GridViewRow row = GridView1.Rows[i]; //this is inside a for loop
var ddl = row.Cells[8].Controls[0] as DropDownList;
string test= ddl.SelectedIndex;
I allways get ddl as null when debugging.
So the questions are:
1. How to load the dropdown with 3 values one of them beeing null?
2. How to read the selected dropdown value without using any events like onchange or whatever, example:
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
bool isChecked = chk.Checked;
To answer you quetsions:
You can't set null as a value for a ListItem, because null is not a string literal. null means that the value is missing. null itself is "not a value". So you will need to handle that in your code:
drpList.SelectedValue = dbObj.FieldValue ?? "(n/a)";
I'm not sure what you are asking here. I would suggest using FindControl instead of using indices to access your controls.
As for your problem, Refer below article for dropdownlist in asp.net
http://www.laptrinhdotnet.com/2015/07/su-dung-control-dropdownlist-trong.html

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

Problem finding web control inside of Gridview TemplateField

Okay, so I'm having issues getting the value of a DropDownList that's inside of a TemplateField when updating my GridView. Originally I was using the RowCommand event to check the command name and then performing the appropriate task (update/delete), but I had problems with the event firing twice, so I switched it out for separate events (RowUpdating, RowDeleting). After doing this, FindControl is returning null every time. Just FYI, the gridview is inside of an UpdatePanel that has an AsyncPostBackTriggers for RowEditing, RowUpdating and RowDeleting events.
Here's my TemplateField inside of the GridView:
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:Label
ID="lblMedTypeEdit"
Text='<%# Bind("medDesc") %>'
runat="server">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList
ID="ddlMedTypeEdit"
DataSourceID="srcMedTypes"
SelectedValue='<%# Bind("medtype") %>'
runat="server"
DataTextField="medDesc"
DataValueField="medCode">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
Here is the code I'm using inside of
Protected Sub gvCurrentMeds_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvCurrentMeds.RowUpdating
Dim intRowIndex As Integer = e.RowIndex
Dim ddlMedType As DropDownList = CType(Me.gvCurrentMeds.Rows(intRowIndex).Cells(1).FindControl("ddlMedTypeEdit"),DropDownList)
End Sub
I also tried using a recursive function to find the control (below), but it is still returning back null.
Public Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
If root.ID = id Then
Return root
End If
For Each c As Control In root.Controls
Dim t As Control = FindControlRecursive(c, id)
If Not t Is Nothing Then
Return t
End If
Next
Return Nothing
End Function
If you just want to know what the new value of the dropdown is, this is already provided for you in the NewValues property of the GridViewUpdateEventArgs object passed to the event handler.
In your example, e.NewValues["medtype"] should be the updated value.
You've already specified <%# Bind(...) %> on the dropdown, so ASP.NET will do the work of finding the controls and getting the new values for you - you don't have to plumb the control hierarchy yourself.

Resources