Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
Markdown Monster - The Markdown Editor for Windows

Odd ASP.NET DropDownList DataBinding issue


:P
On this page:

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).

 

 


The Voices of Reason


 

Joe
May 04, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

Rick,
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

Rick Strahl
May 04, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

Joe, I don't usually store anything in viewstate, but rather cache reusable tables on the server. Using Viewstate has too much overhead and both it and chaching wouldn't work in this scenario anyway as the list can change on postbacks as the user modifies the data so you have to reload the list.

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...

Doug Gibbs
May 25, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

I was working on this same problem when I ran across your comments here. I'm using ASP.NET with VB codebehind. I just found that if I took the datareader build and dropdownlist databind() out of the "If Not IsPostBack then" statement (meaning I just copied it and pasted it above the "If" statement) it worked fine. What's up with that? Like you said "odd, odd, odd...."

Doug

Juan B. Gutierrez
May 25, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

I had the same problem with a DropDownList embeded into a custom control. The solution was to remove all assignations to the custom control before invoking DataBind().

Steven
July 21, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

G'day,

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.

Andrew
July 22, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

I had the same problem. Based on Doug and Juan's comments I moved the code from the bottom of the "If Not IsPostBack" to the top.

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


Andrew
July 22, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

I take it back!

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.

Matthew Herrmann
July 24, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

Yep, just came across this exact problem. You need to set SelectedValue to Nothing before databinding (and then set it back to the desired value afterwards).

Venk
August 04, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

Thanks Steven. Your method worked even for me.
Regards.
venk.

Matthew Herrmann
August 21, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

A further comment on this... you may also need to call List.Items.Clear() before setting selectedvalue to nothing. The selectedvalue change does not take in all scenarios.

trinity
September 19, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

i get the same error when i try to edit a datagrid row.

trinity
September 19, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

Please help!!!
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()

Lisa
October 05, 2005

# Odd ASP.NET DropDownList DataBinding issue

I am having these same issue,I put DataBind() method for dropdownlist within If Not Page.PostBack block and hadling under pageload event . But Still I having this error , If anyone can help me , Please post your answer

brett
October 11, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

The answer is above...

set the selectedvalue = null before DataBind()

Vincent
October 27, 2005

# re: Odd ASP.NET DropDownList DataBinding issue

Has anyone checked the deploy version? As in Release versus Debug.

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.

Darrel
January 13, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

THANK YOU for this post and comments. I ran into a similiar problem, but not identical.

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)

Chang
January 17, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

My problem is similar but different.

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.

Chang
January 18, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

I gave up and resulted to manual binding all dropdowns. The problem is that binding the XMLDataSource.Data seems to screw up the binding order of when SelectedValue is binding (there might be other condition that this could happen).

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?).

Paulie
May 23, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

Had this problem and Rebuilt (as opposed to build) the solution.

Worked okay then.

Not the first time that rebuild has worked like this.

Cheers Paulie

Isobel Rae
August 04, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

Thank you so much. I have been battling for days with a databind in VB.net which threw this error. Identical code on a neighbouring listbox worked correctly. I found the quick fix was just to set the selected value to nothing. Yet I never had to do this before, and have built hundreds of listboxes.

Johann Montfort
August 08, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

I have the same error possibly as discussed above, however I cannot seem to manage to solve this

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

rana
September 02, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

hi all
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 :)

Byock
September 04, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

i have the same problem....but all the resolution you gusy have suggested doesn't solve my problem...can you guys help me....

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

Chris
October 06, 2006

# re: Odd ASP.NET DropDownList DataBinding issue

This error is VERY confusing.. my code works fine on one server, but not on another???

Peter B
January 30, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

You should seriously consider EasyListBox.

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

Guigui
February 13, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

I think it's a bug on the framework 2.0.

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

Paul Martin
March 29, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

I have been banging my head against the wall on this for the last 3 days, have unsuccessfully tried all of the suggestions above. I have finally found a solution.

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

Joel
April 10, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

I ran into a similar situation, but don't know if your circumstances are the same. I was data binding a DataValueField that was not unique. So it appears that the ASP.NET DropDownList would bind to the first occurrence of the non-unique data value.

Like I said, don't know if this is the same as your circumstances... but the symptoms were the same.

Hope this helps someone.

drgbg
May 02, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

I have been dealing with a variation of this problem all day and have found a solution to my problem that was not posted here. I tried all the suggestions I found here but none of them worked for me. That may be because I am using VB.NET rather than C#. Clearing the SelectedValue, DropDownList items, resetting the selected property, none of it worked for me (setting the selectedvalue to 0 - did work but was undesireable for other reasons).

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.

Daniel Flippance
May 11, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

Thanks guys, this thread solved my exact same problem:

if (!IsPostBack)
{
...
ddlResorts.SelectedValue = null;
ddlResorts.DataBind();
}

Dan

Enda
July 26, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

Cheers Guys,

.SelectedValue = null;
.DataBind()

does the business

Tim
August 21, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

Thank You!

.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!

Joost
October 23, 2007

# re: Odd ASP.NET DropDownList DataBinding issue

I don't know if someone has already solved it, but I've given the old reflector a spin to see what might be wrong. It seems that there is a bug/inconsistency in the set_SelectedValue of ListControl:

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

Shashank Dwivedi
March 06, 2008

# re: Odd ASP.NET DropDownList DataBinding issue

thanks a lot joy your Solution works for me too.It saved my Time ......Heartly thanks.

tumi
March 18, 2008

# re: Odd ASP.NET DropDownList DataBinding issue

I had the same issue but it was caused by the following text property " Text='<%# Bind("sUsername") >' "

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>

Edy
March 18, 2008

# re: Odd ASP.NET DropDownList DataBinding issue

Here's the REAL solution for this problem. It seems everything has to do with the badly written DropDownList Items editor in Visual Studio:

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.

SweetSasi
March 22, 2009

# re: Odd ASP.NET DropDownList DataBinding issue

Hi Matthew,

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.

ThinkingChair
June 17, 2009

# re: Odd ASP.NET DropDownList DataBinding issue

Thank you very much. Setting the selected value to null before DataBinding worked for me. Glad this post was there.

Jon
March 24, 2010

# re: Odd ASP.NET DropDownList DataBinding issue

I have an oddly acting dropdown.
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.

Kaminski
June 28, 2010

# re: Odd ASP.NET DropDownList DataBinding issue

Setting the DDL.SelectedValue to null fixed this for me. Only happened after VS SP1 applied.

Jon C.
August 23, 2010

# re: Odd ASP.NET DropDownList DataBinding issue

I'm trying to have a user control databound to fields within a database on ASP.NET (.NET 3.5), and, so far haven't come up with anything that binds a <asp:TextBox..> to the database; maybe I'm missing something out, because it seems technologically feasible.

Source code at http://bit.ly/aZZrkq. Tips would be appreciated.

barmenseriff
August 24, 2010

# re: Odd ASP.NET DropDownList DataBinding issue

I just want to say;

{
.Items.Clear();
.SelectedValue = null;
}

technique solves for me in;

VS 2008 Version 9.0.30729.1 SP
.NET Version 3.5 SP1

environment.

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024