How to set Custom Text into DropdownList in ASP.Net - asp.net

I have dropdown list control in one of my application and when I add Items in it from database Its displaying the first Item into Dropdown list by default but I want to display someother text into this like "Select Item from the List" Is there any way I can do this .
Also Can you please help me setting the same value from javascript

On the ASP.NET side of things, you can create the DropDownList with AppendDataBoundItems="true" and any items you bind to it will come after the default:
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<asp:ListItem Text="Select something" Value="-1" />
</asp:DropDownList>
As for doing the same thing completely in Javascript, you can do it with a function like this:
function addFirstItem(list, text, value)
{
var newOption = document.createElement("option");
newOption.text = text;
newOption.value = value;
list.options.add(newOption);
}
addFirstItem(document.getElementById("yourListId"), "Select something", "-1");
Or with jQuery (there is probably something much cleaner, especially for creating a new option tag, but this works):
$("#yourListId option:first").before("<option value='-1'>Select something</option>");

Patridge answer is correct, however if you are using the asp method and still run into a problem, add the items tag to the listitem.
<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
<items>
<asp:ListItem Text="Select something" Value="-1">--Select Something--</asp:ListItem>
</items>
</asp:DropDownList>

Related

Missing something nested in FindControl but always get Null

Literally have read and tried all solutions in Stackoverflow to no avail.
I am trying to get the value of different Dropdownlists genereated from a Repeater and another one just generated on the go, plain and simple.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
I am trying to get all the selectedValue's of all the dropdownLists genereated thru Repeater and the one that is plain and simply there.
<asp:DropDownList ID="reasonFamily" runat="server">
<asp:ListItem Enabled="true" Text="--------" Value="-1"></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
which looking in the front end, I am getting something like...
<select name="ctl00$ContentPlaceHolder1$reasonFamily" id="ContentPlaceHolder1_reasonFamily">
Which looks good, since I did a button and tried to get this value...
DropDownList ctr = Page.FindControl("Content2").FindControl("reasonFamily") as DropDownList;
TextBox.Text = ctr.SelectedValue;
I could just get the value of reasonFamily.SelectedValue and get finished with... But the problem is, there is another section with a repeater that creates several DropDownList and I need to find all of them and get all their values and Send them to the DB. The DropDownList is all nested in...
<asp:Repeater ID="repStudents" runat="server">
<asp:DropDownList ID="reasonStd" runat="server">
<asp:ListItem Enabled="true" Text="--------" Value="-1"></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
I tried getting finding all of the dropdownlist, but all I get is NULL.
UPDATE: I was able to get the one that is not in the Repeater, but other still eludes me, even tho I have almost tried all the possible choices.
<select name="ctl00$ContentPlaceHolder1$reasonFamily" id="ContentPlaceHolder1_reasonFamily"> // This I was able to access with:
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("reasonFamily") as DropDownList;
<select name="ctl00$ContentPlaceHolder1$repStudents$ctl01$reasonStd" id="ContentPlaceHolder1_repStudents_reasonStd_1"> //This I could not. Tried all of this:
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("reasonStd_1") as DropDownList;
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("repStudents").FindControl("reasonStd_1") as DropDownList;
DropDownList ctr = this.Master.FindControl("ContentPlaceHolder1").FindControl("repStudents")FindControl("reasonStd").FinControl("1") as DropDownList;
Ok, so the 2nd or some other repeater issue - we leave that separate for now.
that last answer SHOWS how we can grab those values - it really the same code.
So, you have a repeater. It has maybe 1 or 15 rows. So, we want to get/grab the drop down list from each row of the repeater.
So, say we have this markup in the repeater (I included your above dropdown list).
So, we have this simple markup:
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px">
<div style="padding:5px;text-align:right">
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
<asp:DropDownList ID="reasonFamily" runat="server">
<asp:ListItem Enabled="true" Text="--------" Value="-1"></asp:ListItem>
<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>
</asp:DropDownList>
<br />
</div>
</div>
</ItemTemplate>
Ok, now it don't matter if this has 2, or 30 rows. Lets assume it has 3 rows of data. so the above now shows this:
So say when we click on the above button, then we need code (the SAME code in the last question). so the code to process each row, get the values (including the dropdown) could be like this for that button click:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (RepeaterItem rRow in Repeater1.Items)
{
// get First Name.
Debug.Print(rRow.FindControl("txtFirst") as TextBox.Text);
// get LastName
Debug.Print(rRow.FindControl("txtLast") as TextBox.Text);
// get value of drop down box
string strDropDownChoice = rRow.FindControl("reasonFamily") as DropDownList.Text;
Debug.Print("Drop Down option picked = " + strDropDownChoice);
}
}
And output from above loop code would be this:
Output:
Albert
Kallal
Drop Down option picked = 1
Darcy
Caroll
Drop Down option picked = 2
Don
Grant
Drop Down option picked = 2
So, once again, I don't see any real issue or problem with looping over the rows in the data repeater, and then pulling out the values from text box, check box, or a drop down list - it is all quite much the same.

'ddpJobType' has a SelectedValue which is invalid because it does not exist in the list of items

im trying to bind the data from database to dropdownlist and i want to set the default value as "select". but i got this error.
My Code is:
<asp:DropDownList ID="ddpJobType" runat="server" Width="226px" Height="26px"
onselectedindexchanged="ddpJobType_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="0" Text="--Please Select Type--"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ErrorMessage="Please Select JobType " Font-Size="Small"
ForeColor="Red" ControlToValidate="ddpJobType"
ValidationGroup="VGPJobPost"></asp:RequiredFieldValidator>
If you are banding data using DataSource, then your default item will not be available after the call of DataBind function. You need to add it manually after calling databind something like below
dropDownList.DataSource= yourdataSource;
dropDownList.DataBind();
dropDownList.Items.Insert(0, new ListItem("--Please Select Type--", "0"));
Another option is in the designer you need to specifiy
AppendDataBoundItems=true
This will make sure your designtime list items are present after databind

Select multiple value in DropDownList using ASP.NET and C#

Select multiple value in DropDownList using ASP.NET and C#. I tried it to select single value from drop down but unable to find multiple selection.
In that case you should use ListBox control instead of dropdown and Set the SelectionMode property to Multiple
<asp:ListBox runat="server" SelectionMode="Multiple" >
<asp:ListItem Text="test1"></asp:ListItem>
<asp:ListItem Text="test2"></asp:ListItem>
<asp:ListItem Text="test3"></asp:ListItem>
</asp:ListBox>
Take a look at the ListBox control to allow multi-select.
<asp:ListBox runat="server" ID="lblMultiSelect" SelectionMode="multiple">
<asp:ListItem Text="opt1" Value="opt1" />
<asp:ListItem Text="opt2" Value="opt2" />
<asp:ListItem Text="opt3" Value="opt3" />
</asp:ListBox>
in the code behind
foreach(ListItem listItem in lblMultiSelect.Items)
{
if (listItem.Selected)
{
var val = listItem.Value;
var txt = listItem.Text;
}
}
Dropdown list wont allows multiple item select in dropdown.
If you need , you can use listbox control..
ASP.NET List Box
For multiple selection dropdown list,cannot accomplish it directly using dropdown..Can be done in similar ways..
Either you have to use checkbox list or listbox (ajax inclusive)
http://www.codeproject.com/Articles/55184/MultiSelect-Dropdown-in-ASP-NET
http://social.msdn.microsoft.com/Forums/vstudio/en-US/54374df7-5a54-42bc-83b8-ad5994cb634d/multi-select-dropdownlist
http://www.dotnetfunda.com/articles/article1591-multiselect-dropdownlist-in-aspnet-using-csharp-40-.aspx

disable button until value is selected ---select---doesnt appear

SO far everything working ok, button is disabled until value is selected from the drop down list,
However I want ---select--- to be the first option on the drop down list, but this is not happening...any ideas as to why?
<asp:DropDownList ID="DropDownListSubContractors" runat="server"
AppendDataBoundItems="true" DataTextField="Company_Name" DataValueField="id"
onchange='selectChanged(this);'>
<asp:ListItem Text="---Select---" Value="0" />
<asp:ListItem Text="Option 1" Value="1" />
</asp:DropDownList>
<script type="text/javascript">
function selectChanged(e) {
document.getElementById("<%= addNewSubContractor.ClientID %>").disabled
= (e.options[e.selectedIndex].value == "0") ? "disabled" : "";
}
</script>
<asp:Button ID="addNewSubContractor" Text="Add Sub Contractor"
OnClick="UploadSubContractor" runat="server" disabled='disabled' />
Showing the manually added items first followed by the data bound items is the default behavior of the drop down list, so ---Select--- should in theory be the first item.
I suspect there is some logic elsewhere(can be javascript or code behind) which sets the selected item to something else i.e:
DropDownListSubContractors.SelectedIndex = 1;
Have a good look through your code and make sure the selected item is not being re-set anywhere
Have you got append databound item set to true, this checks to see if there are any items in the collection, and adds them first before binding?

asp.net dropdownlist - add blank line before db values

On my page I have a DropDownList which I populate with database values from an SqlDataSource (see code below).
How can I add my own text or a blank line before the values?
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id">
</asp:DropDownList>
<asp:SqlDataSource ID="dsClients" runat="server"
ConnectionString="my_connection_string"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [client_id], [name] FROM [clients]">
</asp:SqlDataSource>
Thanks.
P.S. Do you recommend using a SqlDataSource or is it better to populate another way?
You can simply add a ListItem inside the DropDownList Markup. All the values from the DataSource will be appended after that.
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id" AppendDataBoundItems="true">
<asp:ListItem>-- pick one --</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id" AppendDataBoundItems="True">
<asp:ListItem Text="" Value="" />
</asp:DropDownList>
It's easy to miss, so don't forget the AppendDataBoundItems attribute I added.
I haven't really tested this but I'm assuming that you could add an item after you have binded the the drop down list. You could add this event to any dropdown list you'd like to add this empty box to.
protected void DropDownList_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ListItem emptyItem = new ListItem("", "");
ddl.Items.Insert(0, emptyItem);
}
I solve changing the select command adding an empty option:
<asp:SqlDataSource ID="dsClients" runat="server"
ConnectionString="my_connection_string"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [client_id], [name] FROM [clients] union SELECT NULL, '--- pick one ----' ">
</asp:SqlDataSource>
Greetings!!!
In razor-style implementation at me it looks like this:
#Html.EnumDropDownListFor(
model => model.Privilege.Role,
"-- Select role --",
new
{
#style = "width: 216px !important",
#class = "form-control",
id = "role",
required = "required"
})
And in javascript which is executed on load I have this:
function PutDefaultPrivilegePanelListHints() {
$('#role').val('');
...
}
There is also more flexible solution via unobtrusive validation (not to count on HTML5):
$('.required').each(function () { $(this).rules('add', { required: true, messages: { required: '' } }) });
Of course, there is a server-side check, too.
I don't think it's a good idea to cope with classes.
For instance, everything I show in the page is some class. This class has several enumerable type properties. It would be a nightmare to replicate all those properties, but making them nullable in some additional class as some ones suggested here on stackoverflow.
After all, why should i change my business logic for the sake of some specific markup? Instead, I deal with everything via javascript and some model checks.

Resources