I just want an ASP.NET DropDownList with no selected item. Setting SelectedIndex to -1 is of no avail, so far. I am using Framework 3.5 with AJAX, i.e. this DropDownList is within an UpdatePanel.
Here is what I am doing:
protected void Page_Load (object sender, EventArgs e)
{
this.myDropDownList.SelectedIndex = -1;
this.myDropDownList.ClearSelection();
this.myDropDownList.Items.Add("Item1");
this.myDropDownList.Items.Add("Item2");
}
The moment I add an element in the DropDown, its SelectedIndex changes to 0 and can be no more set to -1 (I tried calling SelectedIndex after adding items as well)... What I am doing wrong? Ant help would be appreciated!
Bare in mind myDropDownList.Items.Add will add a new Listitem element at the bottom if you call it after performing a DataSource/DataBind call so use myDropDownList.Items.Insert method instead eg...
myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();
myDropDownList.Items.Insert(0, new ListItem("Please select", ""));
Will add the 'Please select' drop down item to the top.
And as mentioned there will always be exactly one Item selected in a drop down (ListBoxes are different I believe), and this defaults to the top one if none are explicitly selected.
I am reading the following:
http://msdn.microsoft.com/en-us/library/a5kfekd2.aspx
It says:
To get the index value of the selected item, read the value of the SelectedIndex property. The index is zero-based. If nothing has been selected, the value of the property is -1.
In the same time, at http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.selectedindex(VS.80).aspx we see:
Use the SelectedIndex property to programmatically specify or determine the index of the selected item from the DropDownList control. An item is always selected in the DropDownList control. You cannot clear the selection from every item in the list at the same time.
Perhaps -1 is valid just for getting and not for setting the index? If so, I will use your 'patch'.
It's possible to set selectedIndex property of DropDownList to -1 (i. e. clear selection) using client-side script:
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="A"></asp:ListItem>
<asp:ListItem Value="B"></asp:ListItem>
<asp:ListItem Value="C"></asp:ListItem>
</asp:DropDownList>
<button id="СlearButton">Clear</button>
</form>
<script src="jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#СlearButton").click(function()
{
$("#DropDownList1").attr("selectedIndex", -1); // pay attention to property casing
})
$("#ClearButton").click();
})
</script>
I'm pretty sure that dropdown has to have some item selected; I usually add an empty list item
this.myDropDownList.Items.Add("");
As my first list item, and proceed accordingly.
The selectedIndex can only be -1 when the control is first initalised and there is no items within the collection.
It's not possible to have no item selected in a web drop down list as you would on a WinForm.
I find it's best to have:
this.myDropDownList.Items.Add(new ListItem("Please select...", ""));
This way I convey to the user that they need to select an item, and you can check SelectedIndex == 0 to validate
Create your DropDown list and specify an initial ListItem
Set AppendDataBoundItems to true so that new items get appended.
<asp:DropDownList ID="YourID" DataSourceID="DSID" AppendDataBoundItems="true">
<asp:ListItem Text="All" Value="%"></asp:ListItem>
</asp:DropDownList>
Please try below syntax:
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("Select"))
or
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("SelectText"))
or
DropDownList1.Items.FindByText("Select").selected =true
For more info :
http://vimalpatelsai.blogspot.in/2012/07/dropdownlistselectedindex-1-problem.html
Related
Each ListItem in an ASP.NET has a value property and a text property. I need to have a third value saved also. My hack is to concatenate a special separator and the third value to the Value property.
But using FindByValue method makes this cumbersome.
Is there a better way to save the third value or a good way to use FindByValue. (I can't use FindByText). I wish there was a Tag property.
If you are using a binded DropDownList, defined with the DataTextField and DataValueField properties, there's not really a good way to save the third value on the DropDownList itself. You could save it separately tho.
If you're defining your DropDownList through the markup, you could try defining it as a custom attribute:
<asp:DropDownList ID="ddlDummy" runat="server">
<asp:ListItem Text="x" Value="y" ThirdValue="z" />
</asp:DropDownList>
For retrieving it, you could use FindByValue and get the ThirdValue attribute from the ListItem:
ListItem item = ddlDummy.Items.FindByValue("y");
string value = item.Attributes["ThirdValue"];
However, weirdly, if you generate the items dynamically, the attributes will not be persisted:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ListItem item = new ListItem("x", "y");
item.Attributes.Add("ThirdValue", "z");
ddlDummy.Items.Add(item);
}
}
If this is your case, you could take a look at this question that gives a work arround:
ListItems attributes in a DropDownList are lost on postback?
How to get the textbox value on code-behind after the textbox value assigned on a modal-box?
This is how the modal-box appear on the page:
<div id="dialog-form" title="Modal Box">
<asp:TextBox ID="Textbox1" runat="server" ReadOnly="True">
<asp:Button ID="Save_Button" runat="server" Text="Save"></asp:Button>
</div>
In order to assign the value on Textbox1, I attach a Javascript function to the LinkButton on a Gridview (the code not showed here) through code-behind based on the LinkButton clicked:
Dim myLinkButton As LinkButton
For i As Integer = 0 To GV1.Rows.Count - 1
myLinkButton = DirectCast(GV1.Rows(i).Cells(1).FindControl("LinkButton"), LinkButton)
myLinkButton.Attributes.Add("onclick", "shopModalPopup('" + .Rows(i).Cells(0).Text & "'); return false;")
Next
Rows(i).Cells(0) is the first column on the Gridview, it is "ID". This ID will be assigned to the Textbox1 while the Linkbutton clicked.
The Javascript code is on the same page as the Gridview code:
<script>
var grid_modal_options = {
height: 450,
width: 550,
modal: true
};
function shopModalPopup(id) {
var DataField = id;
grid_modal_options.open = function () {
$('#dialog-form #Textbox1').val(DataField);
};
$("#dialog-form").dialog(grid_modal_options);
$("#dialog-form").parent().appendTo('form:first');
}
</script>
When I clicked the Save Button on the modal-box, the value on the Textbox1 can't catch on the code-behind. It always return null value. How to do that? Thank you very much.
please read this
http://www.codeproject.com/Articles/37090/JQuery-UI-Dialog-with-ASP-NET-empty-post-values
i think it might help you the problem might be that the div of dialog is moved outside the form you can solve it by using reference above or just defining another hidden input and update the hidden input with the same value
$('#dialog-form #Textbox1').val(DataField);
$('hiddenfield').val(DataField);
and then read the value from the hidden field
not sure if it the best answer but might work as a quick fix
Does it work without Readonly="true"? If so, in your <asp:textbox>, replace Readonly="true" with Enabled="false".
I haven't tested this, but i recalled Readonly causing me issues like this in the past.
Hey I have a radiobuttonlist and trying to set one of the radiobuttons to selected based on a session variable but proving impossible.
<asp:radiobuttonlist id="radio1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:listitem id="option1" runat="server" value="All"/>
<asp:listitem id="option2" runat="server" value="1" />
<asp:listitem id="option3" runat="server" value="2" />
</asp:radiobuttonlist>
I.e How can I set option2 to selected in code behind ?
The best option, in my opinion, is to use the Value property for the ListItem, which is available in the RadioButtonList.
I must remark that ListItem does NOT have an ID property.
So, in your case, to select the second element (option2) that would be:
// SelectedValue expects a string
radio1.SelectedValue = "1";
Alternatively, yet in very much the same vein you may supply an int to SelectedIndex.
// SelectedIndex expects an int, and are identified in the same order as they are added to the List starting with 0.
radio1.SelectedIndex = 1;
You could do:
radio1.SelectedIndex = 1;
But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!
Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately. For instance:
//omitting possible null reference checks...
var wantedOption = radio1.FindControl("option2").Selected = true;
Try this option:
radio1.Items.FindByValue("1").Selected = true;
We can change the item by value, here is the trick:
radio1.ClearSelection();
radio1.Items.FindByValue("1").Selected = true;// 1 is the value of option2
var rad_id = document.getElementById('<%=radio_btn_lst.ClientID %>');
var radio = rad_id.getElementsByTagName("input");
radio[0].checked = true;
//this for javascript in asp.net try this in .aspx page
// if you select other radiobutton increase [0] to [1] or [2] like this
I have a DataBound DropDownList that is loading fine, but i'd like to insert another item that says "--Select--" or something instead of having the first DataBound item automatically display.
Is there an easy way to do this or do I need to manually add a dummy item?
Here is my code:
MyContext fc = new MyContext ();
ddl.DataSource = fc.SomeTable;
ddl.DataBind();
Alternatively, add a default item in the markup and set the "AppendDataBoundItems" property to true.
<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="" Text="---Please Select---"></asp:ListItem>
</asp:DropDownList>
After you do the databind do:
ddl.Items.Insert(0, "---Select---");
This will add it as the first item in the list.
Alternatively, you can add a new ListItem instead of a string, so you can have an actual value instead of a string as drop down list value.
So you can do something like:
ddl.Items.Insert(0, new ListItem("---Select---", Guid.Empty.ToString());
For my ASP.NET page, in the code behind I load various items/options into a DropDownList but I do not set a default by assigning SelectedIndex. I notice for the postback SelectedIndex is set to 0, even if I never set focus to or changed the value in the DropDownList.
If not otherwise specified in the code behind or markup, will a default value of 0 be used for the SelectedIndex in a postback with a DropDownList? If yes, is this part of the HTML standard for selection lists, or is this just the way it is implemented for ASP.NET?
This is normal behavior for the HTML SELECT control.
Unless the selected property is used, it will always start at the first item (index of 0).
In many cases, I don't want this in ASP.NET because I specifically want the user to select an option.
So what I do is add a blank item which I can then validate.
i.e.
<asp:DropDownList runat="server" DataSourceID="SomeDS" AppendDataBoundItems="true"> // Notice the last property
<asp:ListItem Text="Please select an option" Value="" />
</asp:DropDownList>
This way, I can set a validator which checks if the value is blank, forcing the user to make a selection.
For anybody looking for a way to do this from the code behind, you can add the extra list item there by using the Insert function and specifying an Index of 0, as mentioned in this SO Question. Just make sure to do so after you've called DataBind()
myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();
myDropDownList.Items.Insert(0, new ListItem("Please select", ""));