ddl Selected Index vs Selected Value

Obviously I'm missing something...in all my debugging I find that when trying to set the selectedindex to my dropdownlist that all previous logic goes out the window!  In standard VB, setting the selectedindex meant referring to it's option value.  What I find now is there is a distinct index array collection not based on the listitem value.

To summarize, I have a datagrid with template column that contains a read-only textbox for it's Item Template and a dynamic dropdownlist for it's Edit Item Template. When the edit hyperlink command is clicked, I grab the text value from the textbox and call to database to get the recordid for the value which will then server as the listitems "value" along with it's original "text" value.
This is the code that I am trying to use to set the selectedindex for the dropdownlist after binding the data: (note: strValue is the value found for the 'option value' for the listitem)
CType(e.Item.FindControl("gridPageDropDown"), DropDownList).SelectedIndex = CType(e.Item.FindControl("gridPageDropDown"), DropDownList).Items.IndexOf(CType(e.Item.FindControl("gridPageDropDown"), DropDownList).Items.FindByValue(strValue))
While stepping through debug, I find that strValue is set correctly...ie: "3" but at this line of code I get the following error:
System.NullReferenceException: Object reference not set to an instance of an object
and here is the stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
CSPD.pageadmin.pagesGrid_EditCommand(Object source, DataGridCommandEventArgs e) in C:\BACKUP_WEBSITES\CSPD\UserControls\pageadmin.ascx.vb:135
System.Web.UI.WebControls.DataGrid.OnEditCommand(DataGridCommandEventArgs e) +110
System.Web.UI.WebControls.DataGrid.OnBubbleEvent(Object source, EventArgs e) +466
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
System.Web.UI.WebControls.DataGridItem.OnBubbleEvent(Object source, EventArgs e) +100
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +26
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +120
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +115
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +18
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +138
System.Web.UI.Page.ProcessRequestMain() +1263
ANY DIRECTION WOULD BE HIGHLY APPRECIATED
SCHLEYER
0
schleyer
3/8/2004 10:28:07 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

3 Replies
976 Views

Similar Articles

[PageSpeed] 6

I'm wondering why you wrote this the way you did:
CType(e.Item.FindControl

("gridPageDropDown"), DropDownList).SelectedIndex = CType(e.Item.FindControl
("gridPageDropDown"), DropDownList).Items.IndexOf(CType(e.Item.FindControl
("gridPageDropDown"), DropDownList).Items.FindByValue(strValue))
Are you working on an entry for a "Most obfusicated code" contest or something? Try breaking it down into its parts. You'll find that its a whole lot easier to understand and debug. Or do you plan on never sleeping between the time you write it and the time you have to modify it when the users come up with a change? Try doing it like this

Dim ddl As DropDownList = CType(e.Item.FindControl("gridPageDropDown"), DropDownList)
Dim itm As ListItem = ddl.Items.FindByValue(strValue)
If Not itm Is Nothing Then ' allow for a not-found condition
ddl.ClearSelection() ' in case there was a prior selection
itm.Selected = True
End If
You don't even need to know the selected index in this code. If you are 100% certain that the item will always be there to be found, you could omit the "If Not Itm Is Nothing", and if you're certain there will never be an item already selected, you can omit the "clearSelection". I don't think there can be more than one opinion over which code is easier to write, understand and debug.
Sorry to pick on your code that way. But I think the way it is written is a big part of why you're having a hard time figuring out what's wrong with it.
Jim


MS MVP ASP.NET [VC++/MFC emeritus]


Old Dog Learns New Tricks

Preferred programming language: cuneiform on clay tablets
0
JimRoss
3/8/2004 10:57:46 PM
Thank you for setting me straight on complexity...I knew my code was getting outta control because of that...that's why I posted...I've worked and researching so much on this that I'm was truly lost

I posted the above code, but realized that my orig logic was off...I was trying to findcontrol after all the databinding was done and there is one ddl per row in my datagrid.
Now am having another problem...hopefully minor. I inserted an onload into my asp:dropdownlist tag and placed the code in that sub...code is below
<EditItemTemplate>
<asp:DropDownList ID=gridPageDropDown runat=server datavaluefield="pageid" DataTextField="pagename" DataSource="<%#TempDataView%>" onload="<%# SetIndex(source,args)%>"></asp:DropDownList>
</EditItemTemplate>
Public Sub SetIndex()
Dim connection As New SqlConnection(connectionString)
connection.Open()
Dim strSQL As String
strSQL = "SELECT pageid FROM pages where pagename = '" & Replace(gridPageDropDownValue.ToString, "'", "''") & "'"
Dim objCmd As SqlCommand = New SqlCommand(strSQL, connection)
Dim strValue As Object = CStr(objCmd.ExecuteScalar())
Dim ddl As DropDownList = CType(pagesGrid.FindControl("gridPageDropDown"), DropDownList)
'''Dim ddl As DropDownList = gridPageDropDown
Dim itm As ListItem = ddl.Items.FindByValue(strValue)
If Not itm Is Nothing Then ' allow for a not-found condition
ddl.ClearSelection() ' in case there was a prior selection
itm.Selected = True
End If
connection.Close()
End Sub
----------------
The code doesn't error, but it still doesn't select the item. I modified your original code because I didn't have the 'e' args since this is custom function. The 'gridPageDropDown' didn't automatically inhert in my codebehind...assuming that's because the ddl is embedded withint the datagrid. I typed it in manually like:
Protected WithEvents gridPageDropDown As System.Web.UI.WebControls.DropDownList
and then tried using the commented code above, but no luck.
PLEASE FORGIVE MY FRUSTRATION AND IGNORANCE...I have learned so much in .NET and have not had such issues with anything else...
Schleyer
0
schleyer
3/8/2004 11:39:17 PM
STILL UNRESOLVED
0
schleyer
3/9/2004 1:10:59 AM
Reply:

Similar Artilces:

Form: Focus on selected values in dropdownlists, Refresh after selection and hidding formfields based on selection.
Hello again,I have a form with several dropdown lists. Depending on the selected value in the dropdown lists other fields become available in that same form. It is working in classic ASP in combination of JavaScript. I want to migrate it to ASP.NET. I have posted a part of the form at the end of this post.My questions:1. I use <option <%If iFood="0" then%>selected<%End If%> value="0">No value selected</OPTION> to select the selected item when the form is reloaded after the selecting. I know that this also works in ASP.NET, but isn't there a typical ASP....

dropdownlist's selected index value is not printing the selected value
Here iS my code .Aspx Page <asp:DropDownList ID="ddlkeyword" runat="server" Width="204px" DataTextField="Form" DataValueField="Form" OnSelectedIndexChanged="ddlkeyword_SelectedIndexChanged" >   </asp:DropDownList> <asp:Button ID="Button1" runat="server" Text="Submit" Width="110px" OnClick="Button1_Click" /> my aspx.cs protected void Page_Load(object sender, EventArgs e) { fillddlkeyword(); }protected void Page_Init(object sender, EventArgs e) { ...

ListBox selected index change problem with selected value
I have a problem with my list box selected index changed. There are two items in the list box one is a Group Name and then below each group are email addresses that go with those groups. When I select the group name it puts the selected value where it is equal to group_id  the select statement looks like this and works correctly: SELECT d.group_descr, a.first_name, a.last_name, a.user_id, b.email, d.group_id, d.parent_group_id FROM icc_user_data AS a LEFT OUTER JOIN icc_users AS b ON a.user_id = b.user_id LEFT OUTER JOIN icc_users_groups AS c ON a.user_id = c.user_id LEFT OUTER JOIN ...

form text, selectable/copyable vs not selectable/copyable
How does one produce selectable/copyable text on a VCL form (with appearance/function as that provided by TLabel)? My 2007 IDE presents copyright text in the help about box at the top that is selectable/copyable. That same box toward the bottom presents OS/memory information that is not selectable/copyable. Both have same general appearance. Why is one selectable/copyable and the other is not? A TLabel's caption text does not seem to be copyable, is there an option I've overlooked to make it selectable/copyable, if so what? Bonus appreciation for more info, sa...

SELECT from SELECT
Hi! I remember seeing an example where you can do a select from a nested select, but I cannot seem to make it work. So it would be something like this: select max( name ) from ( select name from customer union select name from vendor ) Was I dreaming I saw that? Thanks! D In article <4500243f@forums-2-dub>, daniel_AT_infrontsoftware_DOT_com@N0SPAM.com says... > Hi! > > I remember seeing an example where you can do a select from a nested > select, but I cannot seem to make it work. No, you weren't. Try (UNTESTED!) adding a...

Capturing DDL selected value and or index
I have a DDL that has DB generated values.  There is an added option "Not Listed".  If the user selects this option I would like to show a label "Please enter a name" and a textbox to capture that data.  The label and textbox visibility is set to false when the page is loaded.  Selecting "Not Listed" needs to show the label and textbox I have tried to create a selectedIndexChanged function but cannot get it to work. Can anyone help me? ***** NEWBIE ALERT ***** I am coding in C# and would appreciate a complete code example if at all poss...

DropDownList Selected value to set gridview selected Index and page
I have a dropdownlist and a gridview that is bound to the same objectdatasource. In the gridview I am allowing paging.  When user select an item in the dropdownlist list I want to position the gridview selected value to that page and that record. Is there an easy way to do this. I tried this code Protected Sub GrdMyIssues_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GrdMyIssues.RowDataBound If e.Row.RowType = DataControlRowType.DataRow Then 'find the position data selected in the If e.Row.Cells(1).Text = Me.ViewSt...

How to use Select case statement to select web form controls
Hi; I don't know why I can't conceptionalize  this but I want to take these if statements and put them in a select case. I am testing for multiple selection from several DDLs on my web form.   If DropDownList1.SelectedIndex > -1 And DropDownList2.SelectedIndex > 0 Then If Me.CheckBox1.Checked Then ObjectDataSource1.FilterExpression = "assignee = {0} AND assignor = {1}" Else ObjectDataSource5.FilterExpression = "assignee = {0} AND assignor = {1}" End If End If If DropDownList1.SelectedIndex > -1 And DropDownList3.SelectedIndex >...

Dropdownlist selected value passes first value in list no matter what value is selected. why ?
 HI . I have a dropdownlist. Databinds ok but when I must pass a value as a Selected value it always passes the first value in the list even if I select another value. I tried to set the ddl to enableviewstate false but it doesn't change anything. Any ideas ? Code below, thanksLoading the ddl:       productCategories = CatalogAdmin.Admin_Product_Categories_NotIn(productId);        for (int i = 0; i < productCategories.Rows.Count; i++)        {       &...

Forms , Select and option selected.
Name: Jirrick Email: jurahudecatgmaildotcom Product: Firefox Release Candidate Summary: Forms , Select and option selected. Comments: I've found problem with SELECTED option in <select> forms. I wanted to use pre-selected option in my form , but when I used the Firefox 3 RC1 to render it there wasn't any preselected item. I tried to rewrite code ( use selected="selected" ) , but still no effect. I was confused and tried to use others viewers ( IE 8 , OP 9 , Konqueror ) and the pre-selected item worked well in these browsers. The bug has to be in FF 3 ...

SELECT * vs. SELECT 1
I have always understood that when using the WHERE EXISTS clause, one codes it as WHERE EXISTS (SELECT * FROM .....). Lately, I've been told that performance is better if the it's coded as ...(SELECT 1 FROM ...) (or SELECT '' .. - that is, to select some literal). Everything I've read says that SELECT * is used with EXISTS because there's no result set returned - it only evaluates into true or false. I'm now curious - is there an advantage to writing SELECT 1 instead of SELECT * with EXISTS? If so, how much of an advantage, & why do all of the SQL b...

Select into vs. insert ... select ...
Hello, I am using temp tables to generate a report. I created most of the temp tables and then use insert select. I found for one that when I use insert select I get a different query plan that if I use select into. The select into get a much better performance. The problem is I get dead lock on the statement. Is there anything I can do to change this behavior? Thanks, Josh Manfred SELECT INTO #temp is a non-logged operation. This can provide a performance increase. However, one downside is that you may end up with a lot of contention on system tables. (I didn...

Accessing the selected value from a Select
Need to access the selected value from a Select in client script.  I can get the selectedIndex but where do I find the selected value? Will this give it to me? form1.Select1.Options(form1.Select1.SelectedIndex)   form1.Select1.options[form1.Select1.selectedIndex] Try form1.Select1.options[form1.Select1.selectedIndex].value> penny for a thought...

select into vs insert/select
I am looking for ways to speed up a procedure, which as a part of an overnight processing is called about 3000 times. The procedure begins by inserting about 20 rows into a temp table created outside of the proc. I thought that this may be better done by a select into statement because it is minimally logged etc. I am running the two versions of the statement (insert/select and select into) 2700 times on a quiet server and it seems that the insert/select is a bit faster, a second or two. Any ideas what I'm doing wrong? Is it my assumption about select into being fas...

Web resources about - ddl Selected Index vs Selected Value - asp.net.web-forms

Portal:Bollywood/Selected biography - Wikipedia, the free encyclopedia
Write three or four paragraphs in the text field using information from the selected notable article, you may find it useful to examine the existing ...

F8: Facebook’s FbStart Initiative Will Give Selected Developers A $30K Kick-Start
... successful applications is likely a whole lot easier with $30,000 in free tools and services to start off with, and that’s exactly what selected ...

LEGO Shop - The LEGO Technic team has selected the winner... - Facebook
The LEGO Technic team has selected the winner of the Co-Creation Challenge! LEGO will be producing a limited run of 20,000 of this stunning set.... ...

Grand Doctor Ma Selected Students-baby365 on the App Store on iTunes
Get Grand Doctor Ma Selected Students-baby365 on the App Store. See screenshots and ratings, and read customer reviews.

Selected Cheney Vice Presidential Photographs
... for photos found within these albums are Paul Morse, Karen Ballard, Kimberlee Hewitt, Shealah Craighead, and Chris Greenberg. These selected ...

[iOS Advice] How To Clarify Your Email Replies By Quoting Selected Text - YouTube
Follow me on Twitter: http://www.twitter.com/macmixing Like my Facebook page: http://www.facebook.com/macmixing RATE, COMMENT, SUBSCRIBE! :-) ...

UAE Under-19 cricketers for ACC Premier League tour of Malaysia selected - The National
Coach Aaqib Javed seeking fresh blood for senior team after missing out on World Twenty20

Animal of the Day: Lucius Has Been Selected as the U.K.’s ‘Happiest Cat’
He’s got one blue eye, one green eye and a heart of gold. British mobile phone company O2 recently held some “cat auditions” to find “the UK’s ...

Australian director Sue Brooks 'gobsmacked' as Looking for Grace selected for Venice Film Festival competition ...
... filmmaker Sue Brooks says she is "gobsmacked". Her drama Looking For Grace , shot in the Western Australian wheat belt, has been selected for ...

Three Canberra products selected in AFL state combines
Belconnen junior Chris Jansen has been selected in South Australia's state AFL combine.

Resources last updated: 1/19/2016 3:07:49 AM