Odd ASP.NET DropDownList DataBinding issue
I must be having a brain block or something, but for some reason I cannot get a drop down list to databind properly on a postback in ASP.NET.
Check out the following code:
Result = Item.GetItemList("sku,descript",null,"descript");
if (Result > 0)
{
ListItem item = null;
this.cmbParentPk.DataSource = Item.DataSet.Tables["ItemList"];
this.cmbParentPk.DataTextField ="descript";
this.cmbParentPk.DataValueField = "sku";
--> this.cmbParentPk.DataBind();
// *** Add blank item if for items that aren't a subitem
item = new ListItem();
item.Value = "";
item.Text = "*** This item is not a subitem";
this.cmbParentPk.Items.Insert(0,item);
}
This code works fine on a non-postback to the page, but if fails once submitted with a POST on the second hit to the page. I get the following:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: value
Source Error:
|
Line 119: this.cmbParentPk.DataTextField ="descript"; Line 120: this.cmbParentPk.DataValueField = "sku"; Line 121: this.cmbParentPk.DataBind(); Line 122: Line 123: // *** Add blank item if for items that aren't a subitem |
As far as I can tell there’s no invalid data in the table – no nulls or other extended characters. I also checked to make sure there are no duplicate values in the table (although that shouldn't matter anyway). In this case I’m saving an existing inventory item and not even making a change to the data on the page. Simply re-posting.
But the code works fine if I do the binding manually:
Result = Item.GetItemList("sku,descript",null,"descript");
if (Result > 0)
{
ListItem item = null;
foreach(DataRow dr in Item.DataSet.Tables["ItemList"].Rows)
{
item = new ListItem();
item.Value = (string) dr["Sku"];
item.Text = (string) dr["Descript"];
this.cmbParentPk.Items.Add(item);
}
// *** Add blank item if for items that aren't a subitem
item = new ListItem();
item.Value = "";
item.Text = "*** This item is not a subitem";
this.cmbParentPk.Items.Insert(0,item);
}
This works just fine.
So the big question is WTF is ASP.NET choking on? It appears to be the value which would seem to point to some sort of SelectedValue binding, except I’m not doing any binding at that point (there’s some custom databinding using my two-way databinding controls, but this happens much later in the code).
Other Posts you might also like
- Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application
- Resolving Paths To Server Relative Paths in .NET Code
- Map Physical Paths with an HttpContext.MapPath() Extension Method in ASP.NET
- Back to Basics: Rewriting a URL in ASP.NET Core
- Getting the Client IP Address in ASP.NET Core
The Voices of Reason
# re: Odd ASP.NET DropDownList DataBinding issue
The real mystery is just what is blowing up the databinding on a postback. Obviously the databinding with the same data works when binding for the first time.
Viewstate is off and the list doesn't appear to be preloaded when the postback occurs.
Odd, odd, odd...
# re: Odd ASP.NET DropDownList DataBinding issue
Doug
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
I just had the problem myself. My solution was to set the SelectedValue to null before doing the DataBind. MS say to set it to an empty string to unset the DropList value. Looks like they are wrong.
Regards,
Steven.
# re: Odd ASP.NET DropDownList DataBinding issue
Now it works. There are no other references to the dropdown in the code that I moved the DataBind above (there are some further down, but that shouldn't be an issue).
Anyway, go figure. It works now. :p
# re: Odd ASP.NET DropDownList DataBinding issue
The databind was being called after a call to a subprocedure that DID access the dropdown.
However, if the code didn't fail before that, I'm still not sure why it fails when I try to populate it. The code in the subprocedure sets the value of one dropdown equal to another. The weird thing is that later on, the first dropdown gets populated with no errors, the page fails when I try to populate the second dropdown. Anyway, it was my fault for putting the Databind in the wrong spot.
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
Regards.
venk.
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: value]
System.Web.UI.WebControls.ListControl.OnDataBinding(EventArgs e)
System.Web.UI.Control.DataBind()
System.Web.UI.Control.DataBind()
System.Web.UI.Control.DataBind()
System.Web.UI.WebControls.DataGrid.CreateItem(Int32 itemIndex, Int32 dataSourceIndex, ListItemType itemType, Boolean dataBind, Object dataItem, DataGridColumn[] columns, TableRowCollection rows, PagedDataSource pagedDataSource)
System.Web.UI.WebControls.DataGrid.CreateControlHierarchy(Boolean useDataSource)
System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e)
System.Web.UI.WebControls.BaseDataList.DataBind()
polaris.accountdetails.populateDataGrid(DataGrid sDataGridName, DataTable sDataTableName) in c:\inetpub\polaris.dev\accounts\accountdetails.aspx.cs:197
polaris.accountdetails.getUserPriceList() in c:\inetpub\polaris.dev\accounts\accountdetails.aspx.cs:284
polaris.accountdetails.DataGrid4_Edit(Object sender, DataGridCommandEventArgs e) in c:\inetpub\polaris.dev\accounts\accountdetails.aspx.cs:521
System.Web.UI.WebControls.DataGrid.OnEditCommand(DataGridCommandEventArgs e)
System.Web.UI.WebControls.DataGrid.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.DataGridItem.OnBubbleEvent(Object source, EventArgs e)
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)
System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain()
# Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
set the selectedvalue = null before DataBind()
# re: Odd ASP.NET DropDownList DataBinding issue
I made a custom dropdownlist control, and if deployed in Debug mode, it works fine. I compiled it in Release mode, and the DataBind() error occurred.
# re: Odd ASP.NET DropDownList DataBinding issue
In my case, this was on PageLoad...no postback at all. My data would appear to bind (the DDL was populated) but it'd toss up the error mentioned.
Adding the selectedValue = nothing prior to that fixed it.
Now, the big question...WHY does that fix it? ;o)
# re: Odd ASP.NET DropDownList DataBinding issue
My ReadOnly mode is DataBinding with SQLDataSrouce. My Edit mode is DataBinding with XMLDataSource (all in FormView and using controls outside of FormView to change the modes).
Sounds very similar to a bug that supposedely is being fixed:
http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=c9ca5f95-8bd5-4a3a-8386-37a31ae53866
My problem is that in one instance where my DB has an entry of "N/A" which is not in the XMLDataSource (loaded from a php site returning the XML stream - working perfectly) and SelectedValue is binding before the DropDownList has any value because I have a hard coded "N/A" inserted in the template (aspx file) hence there is no way that this could happen. If have a value that exist in the XMLDataSource from the ReadOnly mode then this does not happen. One hint is that it crashes before DataBound which is totally wrong (running under VS2005 debug mode).
I spend like a week trying to figure this out :( If you can help me debug it would be good. My code is too big to be pasted here but the gist is here.
# re: Odd ASP.NET DropDownList DataBinding issue
The most common way that I use the dropdowns is described above. Load the ReadOnly mode from SQLDataSource but load the DropDownList from XMLDataSource in Edit mode. The problem is that in one instance I load the data from a XML stream (not from a file) and the other instance I load the data from a file (which works fine). I hope this is a problem from my stupidity.
I would argue that this setup that I have is more efficient (less DB overhead) for small access (any comment?).
# re: Odd ASP.NET DropDownList DataBinding issue
Worked okay then.
Not the first time that rebuild has worked like this.
Cheers Paulie
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
I have a dropdownlist box, and when there is no value, I am binding a SELECT at the top, as you would do normally:-
ListItem listItem = new ListItem("-- Select --", string.Empty);
list.Items.Insert(0, listItem);
The problem is that when it is SELECT, and I try to select another company from my dropdownlist, and press the update button, it crashes with the following error:-
System.InvalidCastException: Object cannot be cast from DBNull to other types.
Here is my code to bind the company dropdownlist:-
protected void lstCompany_DataBound(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
FormView viewContact = (FormView)list.NamingContainer;
if (viewContact.DataItem != null)
{
string strID = ((DataRowView)viewContact.DataItem)["CompanyID"].ToString();
list.ClearSelection();
ListItem listItem = list.Items.FindByValue(strID);
if (listItem != null)
listItem.Selected = true;
else
list.SelectedValue = null;
}
//add an empty item on top of the list
AddEmptyItem(list);
}
I really appreciate if anyone could help me since I have been 2 days battling out with this problem now
Thanks a lot for your help and time
Johann
# re: Odd ASP.NET DropDownList DataBinding issue
please i need fast help,
im facing the same error but with the table control.
im dragging a table to my page in the design but on a buttom click i create the rows and cells,when i click another buttom to work with the data found in the cells i got this error:
Specified argument was out of the range of valid values...
when i tried to check the row counts,it gives 0,which means no rows found???why, im sure that clicking the first buttom created the rows and i can reach them....
thanks in advance :)
# re: Odd ASP.NET DropDownList DataBinding issue
here's my code
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
PopulateDropdownlist()
End If
Dim strFormat As String
If DropDownList1.SelectedValue = "1" Then
strFormat = "mp3"
ElseIf DropDownList1.SelectedValue = "2" Then
strFormat = "wma"
ElseIf DropDownList1.SelectedValue = "3" Then
strFormat = "aac"
End If
End Sub
*****************
Public Sub PopulateDropdownlist()
Dim ddDR As SqlDataReader = Nothing
Dim ddSqlConnection As SqlConnection = New SqlConnection("server=server;database=database;user id=id;password=password;")
Dim ddSqlCommand As SqlCommand = New SqlCommand("SELECT MediaFormatID, MediaFormat FROM tblMediaFormat order by MediaFormatID ", ddSqlConnection)
ddSqlConnection.Open()
ddDR = ddSqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
DropDownList1.DataSource = ddDR
DropDownList1.DataTextField = "MediaFormat"
DropDownList1.DataValueField = "MediaFormatID"
DropDownList1.Items.Clear()
DropDownList1.DataBind()
End Sub
************
Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim Item As String = CType(DropDownList1.FindControl("DropDownList1"), DropDownList).SelectedItem.Text
PopulateDatagrid(Item)
End Sub
************
PRoblem: The selectedvalue does not change...it is always =1 ....and it doesnot invoke DropDownList1_SelectedIndexChanged even when i clicked the dropdwonlist....
by the way, my autopostback property of my dropdownlist is set to true...
HELP................PLEASE
Thank you
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
http://easylistbox.com/home.aspx?rl=rsblog
Even if a big license is out of your budget, you can get single-website ones through their DotNetCharity promotion (profits from those go to Feed The Children):
http://www.dotnetcharity.com
# re: Odd ASP.NET DropDownList DataBinding issue
The following code is working on framework 1.1 and not on framework 2.0 :
Const STR_ID As String = "ID"
Const STR_LABEL As String = "LABEL"
' Create source
Dim dtDataTable As New DataTable
dtDataTable.Columns.Add(STR_ID, System.Type.GetType("System.Int32"))
dtDataTable.Columns.Add(STR_LABEL, System.Type.GetType("System.String"))
Dim drRow As DataRow = dtDataTable.NewRow
drRow(STR_ID) = 1
drRow(STR_LABEL) = "1"
dtDataTable.Rows.Add(drRow)
' bind
cmbTest.DataSource = dtDataTable
cmbTest.DataTextField = STR_LABEL
cmbTest.DataValueField = STR_ID
cmbTest.DataBind()
cmbTest.SelectedValue = 1
' rebind with error
drRow(STR_ID) = 2
cmbTest.DataSource = dtDataTable
cmbTest.DataTextField = STR_LABEL
cmbTest.DataValueField = STR_ID
cmbTest.DataBind()
On the DataBind line you got an error like this :
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: value
The workaround like wrote above
I add the following code before the second databind :
cmbTest.Items.Clear()
cmbTest.SelectedValue = Nothing
# re: Odd ASP.NET DropDownList DataBinding issue
My situation:
I have a custom user control that contains a drop down list, that when it's SelectedValue is set, the control fills its constituent dropdownlist, and then sets the selected value of the dropdown to the value provided to the usercontrol's SelectedValue property. The control works fine when the property is set manually, but not when the control is included in a template in a GridView control and the SelectedValue is added to the Items Collection of the DropDownList after the Items collection is filled with via data-binding like this...
With ListControl ... binding to data source .Items.Clear() .SelectedValue = Nothing .DataBind() If AddBlank Then .Items.Insert(0, New ListItem(BlankDisplayText, "")) End With
The problem:
I could debug the code on the first row that contained a blank value, and everything seemed to work OK, but before the next row was processed, I got the error described above. Through trial and error, I discovered, that the additional blank item was not in the rendered control, even though I could verify it programatically during the binding phase.
The solution:
It occured to me that the dropdownlist may be databinding again after the databinding created by the setting of the SelectedValue property on my User Control, so I removed the datasource after the .DataBind by setting the .DataSource = Nothing as below.
With ListControl ... binding to data source .Items.Clear() .SelectedValue = Nothing .DataBind() .DataSource = Nothing If AddBlank Then .Items.Insert(0, New ListItem(BlankDisplayText, "")) End With
# re: Odd ASP.NET DropDownList DataBinding issue
Like I said, don't know if this is the same as your circumstances... but the symptoms were the same.
Hope this helps someone.
# re: Odd ASP.NET DropDownList DataBinding issue
In my case, I needed to assign a "-2" to the value property of my "--Select--" item which was added to a DropDownList after databinding to a Key/Value collection object. It would work fine twice but on the third time it would throw this exception:
An exception of type 'System.ArgumentOutOfRangeException' occurred in <dll name>.DLL but was not handled in user code
Additional information: '<control name>' has a SelectedValue which is invalid because it does not exist in the list of items.
Here's the code I was using to handle the DataBinding for the DropDownList Control:
Private Sub BindControl(ByVal cntrl As Object, ByVal DataSource As Object, ByVal DataTextField As String, ByVal DataValueField As String, ByVal AddSelectRow As Boolean, Optional ByVal Value As String = vbNullString)
Try
cntrl.DataSource = DataSource
cntrl.DataTextField = DataTextField
cntrl.DataValueField = DataValueField
cntrl.DataBind()
If (AddSelectRow) Then
Me.AddSelectRow(cntrl, (CStr(IIf(Value = vbNullString, DEFAULT_KEY_VALUE.ToString, Value))))
End If
Catch ex As Exception
Throw ex
End Try
End Sub
This method would crash at the 'cntrl.DataBind()' line.
Here's what fixed the problem:
Add these two lines of code to the top of the method (right after the 'Try' line):
cntrl.DataSource = Nothing
cntrl.DataBind()
This solved the problem for me and I hope it helps someone else out here. Either way, I got mine to work and can now move on to other issues. Good luck with yours.
# re: Odd ASP.NET DropDownList DataBinding issue
if (!IsPostBack)
{
...
ddlResorts.SelectedValue = null;
ddlResorts.DataBind();
}
Dan
# re: Odd ASP.NET DropDownList DataBinding issue
.SelectedValue = null;
.DataBind()
does the business
# re: Odd ASP.NET DropDownList DataBinding issue
.NET VB 2005
In the Handles for ThisDataSet.Updated
DropDownList.SelectedValue = Nothing
DropDownList.DataBind()
The DropDownList/ComboBox will refresh with new data when the page loads.
(You don't need "Nothing" listed as an item in the drop down, resets to the first item in the list.)
This is a known bug they haven't fixed yet!
# re: Odd ASP.NET DropDownList DataBinding issue
What happens is that if the value null is passed in AND there are still items in the list, the selection is cleared through ClearSelection() and afterwards the method returns immediately. Now, what the makers have probably not realized is that the same set_SelectedValue actually caches the last chosen SelectedValue, so when the SelectedValue is set to null while there are still items in the list, this cached value is never updated and is inconsistent with the list control.
The quick way to solve it is to make sure the list is empty BEFORE setting SelectedValue to null, as in (C#):
list.Items.Clear();
list.SelectedValue = null;
list.DataBind();
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
and as soon as I changed the text property to "DataTextField " everything worked like a charm...
<EditItemTemplate>
<asp:DropDownList ID="cboUser" AppendDataBoundItems="true" DataTextField='<%# Bind("sUsername") %>' runat="server" OnLoad="LoadUsers" > </asp:DropDownList>
</EditItemTemplate>
# re: Odd ASP.NET DropDownList DataBinding issue
http://weblogs.asp.net/hpreishuber/archive/2005/08/07/421805.aspx
The key is to set the DropDownList's AppendDataBoundItems property to True and manually add a null item (Value="") item USING THE CODE EDITOR:
<asp:ListItem Text="default" Value=""></asp:ListItem>
The problem is that the DropDownList's Items editor won't let you set an empty value. It will either ignore the empty value field or fill it with whatever you had put in the Text field.
Once this item is available then the DropDownList will perfectly Bind with the DataSource receiving and applying NULL values directly, as with any other value.
# re: Odd ASP.NET DropDownList DataBinding issue
Thanks for the post maddy....Your solution on Matthew Herrmann August 21, 2005 @ 6:48 pm works fine for me...I am struggling for this for a day....and finally got resolved by your solution....once again Thanks.
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
I have a dropdown that is filled with a list of names, this dropdown is filled when the user selects something from a treeview. The names fill in just fine.
i have a textbox under the dropdown, where the user can type the start of a last name and then click a filter button.
The filter button merely runs the same query that was used to fill the dropdown of names, except it now has a where clause of lastname like '[filter text here]%'
then rebinds to the dropdown.
the code behind runs and the query returns the proper records. During debugging I do a quick watch on the items collection of the dropdown and the proper count is displayed.
but when the page redraws ... the full list of names is still displayed.
I put a break point in the procedure used to fill the dropdown and it is only run the one time the filter button calls it (thought perhaps it was running again without a filter value)
I even removed the binding code and tried to loop through the records and manually add the items to the dropdown, same thing ... full list displayed,debugging the do while read loop iterates the correct number of times. Its like the viewstate is ignoring the update from the codebehind
the ddl enable viewstate is true as is the page. I have used this method in the past with no problems, just this one page refuses to cooperate.
Thanks for any ideas anyone might have.
# re: Odd ASP.NET DropDownList DataBinding issue
# re: Odd ASP.NET DropDownList DataBinding issue
Source code at http://bit.ly/aZZrkq. Tips would be appreciated.
# re: Odd ASP.NET DropDownList DataBinding issue
{
.Items.Clear();
.SelectedValue = null;
}
technique solves for me in;
VS 2008 Version 9.0.30729.1 SP
.NET Version 3.5 SP1
environment.
# re: Odd ASP.NET DropDownList DataBinding issue
I do not re-populate the cbo during Postback.
Only on initial page load. Viewstate handles the re-creation of the list. And your 2 way controls unbind the currently selected value back to the BO you bound it to.
e.g.
If IsPostBack Then
UnbindData()
Else
'other page load code here
mNameValueListBO= NVL.GetList()
cboGroupId.DataSource = mNameValueListBO
cboGroupId.DataTextField = "Value"
cboGroupId.DataValueField = "Key"
DataBind()
End If