ASP.NET DropDownList / HTML select list default selection - asp.net

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

Related

How to bind attribute to DropDownList Item on sever side to achieve getting multiple Date Values

I have a dropdownlist, which is getting bind with the datasource on page load.
On SelectedIndexChanged event I need to get multiple values from SelectedItem
I don't want to get one value and call database/session/viewstate to get object with the value.
I search if I can add multiple DataValueField but seems it is not possible, Thus I am thinking to add an attribute to Item and assign additional value field to this attribute.
How can I bind attribute to DDL Item? I tried DataBinding event but don't know how to write code for it. Can anybody help? This is normal asp.net not MVC.
I also tried following (this works for Repeater control):
<asp:DropDownList ID="SetTypes" IsProfiled="<%# DataBinder.Eval(Container.DataItem, "SiteID") %>" runat="server" Width="250" AutoPostBack="True"></asp:DropDownList>
but it seems Container does not have DataItem property.
Try this out:-
SetTypes.DataSource = new List<string>(){
"Type1","Type2","Type3"};
SetTypes.DataBind();
foreach (ListItem item in SetTypes.Items)
{
//Add multiple attributes
item.Attributes.Add("CustomAttribue", "CustomValue");
}

Make multiline textbox remember text input (auto complete)

A normal asp.net textbox will remember your old inputs - if you type something into a textbox and leave the page then come back, and type the same thing. The textbox will "auto complete" what you are typing by suggesting what you typed the last time.
I can see that if you set the Textmode property to "multiline" the textbox then loses it's auto complete. Like this:
<asp:TextBox ID="TextBox_Description" TextMode="MultiLine" MaxLength="500" runat="server"></asp:TextBox>
How do I add this funcitonality to my multiline asp Textbox or a TextArea? (multiline textboxes are rendered as textareas).
I am open to both asp.net specific solutions and javascript/jquery solutions.
You can retrieve what was in the multiline textbox and then cache it and on a postback use the cache to output what was used before.
// Get everything in the multiline text box and cache it
Cache["multilineValues"] = TextBox_Description.Text;
// Output what was written again through cache etc when the page loads after a postback.
//You would most likely put this in the Page_Load method.
if(IsPostBack)
{
if(Cache["multilineValues"] != null)
{
//Use what was written before
TextBox_Description.Text = (string)Cache["multilineValues"];
}
}

Why is my RadioButtonList selectedValue empty?

I have a RadioButtonList:
<asp:RadioButtonList ID="rblMedicationTime" runat="server" onselectedindexchanged="rblMedicationTime_SelectedIndexChanged" DataSourceID="dtsMedicationTime" DataTextField="LookupItem" DataValueField="Id" AutoPostBack="true"></asp:RadioButtonList>
On page load, I want to select a radio button from the list and set its value, for which I have written this line of code:
rblMedicationTime.SelectedValue = clientMedicationSchedule.glTypeId.ToString();
The RadioButtonList is populating successfully, but the value is unable to be selected.
rblMedicationTime.SelectedValue is always "" when I debug the code.
You just need to use
string myValue = myRadioButtonList.SelectedItem.Value
The property object myRadioButtonList.SelectedItem contains all values from the selected item of a Radio Button list or a DropDown list
to set the value programmatically all you have to do is:
myRadioButtonList.SelectedIndex = 0;
You can see that you have several ways to Get but only one to Set:
myRadioButtonList.SelectedIndex --> Gets or Sets
myRadioButtonList.SelectedValue --> Gets
myRadioButtonList.SelectedItem --> Gets
You can't set the selected radiobutton with .SelectedValue, only with .SelectedIndex.
Check MSDN (at SelectedValue it says "Gets the value", at SelectedIndex is says "Gets or sets")
I think problem in !IsPostBack.
if (!IsPostBack)
{
string str = rblMedicationTime.SelectedValue;
}
First you should check !IspostBack
hello friend there is something another problem in your code because in my side this is running fine.
rblMedicationTime.SelectedValue = clientMedicationSchedule.glTypeId.ToString();
can u cehck that clientMedicationSchedule.glTypeId.ToString() this contain value or not.
and on page load u put selection code on if (!IsPostBack){} block.

Devexpress grid - PerformCallback generates Invalid viewstate

I have a DevExpress grid that needs to be refreshed every time the value in a combobox is changed. For example, I have a combobox that sets the grid's page size. One of the requirements is that the combobox does not cause a full postback.
The combobox is declared like this:
<asp:DropDownList ID="cboPages" AutoPostBack="false" runat="server"
EnableViewState="false" OnSelectedIndexChanged="cboPages_SelectedIndexChanged" />
On selected index changed, it sets a cookie whose value is the selected value. When the combobox value changes, a javascript function is called:
function PerformCallbackOnGrid(grid) {
try {
grid.PerformCallback("refresh");
}
catch(err){
alert('Could not perform callback on grid.');
}
}
The function is attached in code behind:
this.cboPages.Attributes["onChange"] = "PerformCallbackOnGrid(" + this.GridClientID + ")";
After performing these steps:
The user changes the grid page size using the combobox, so PerformCallback is called at least once.
The user presses F5(refresh).
The user tries to change the page size again.
an 'Invalid viewstate' error message appears.
I have tried setting ViewStateMode to Disabled for the grid, also EnableViewState="false".
Figgured it out by myself! Apparently it was enough to set
EnableViewState="false" EnableRowsCache="false"
to the grid.
Rows cache was the one causing the viewstate error.

"DropDownList.SelectedIndex = -1" problem

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

Resources