User Control DropDownList Selected Value Not Passed


Edited by SomeNewKid. Please post code between <code> and </code> tags.


Hi,
I'm using C#. I have a user control DropDownList (SearchCategory.ascx) that when included on my page (index.aspx) will not pass the selected value to a simple function in script tags of head content on a button click. It just passes the first value of the list no matter what is selected. I need to pass to the function (in the script tags of head content of index.aspx) the value of a text box (works fine cause it is not a user control) and the value of the DropDownList (only passes the first value of the list) which in turns passes these values to another usercontrol called st. I know this is easy but I have pulled my hair out over it! I have tried it with Viewstate true and false. Any help with this would be much appreciated. Here is my code:
----------User Contol DropDownList------------
<%@ Import Namespace="System.Data.SqlClient" %>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<script runat="server" language="c#">
protected DataSet objDS;
public void Page_Load() {

//Search Category Data Binding from XML File
objDS = new DataSet();
objDS.ReadXml(MapPath("xml/search_category.xml"));
searchCategoryDropDownList.DataSource = objDS;
searchCategoryDropDownList.DataValueField = "Value";
searchCategoryDropDownList.DataTextField = "Name";
searchCategoryDropDownList.DataBind();
objDS.Clear();

}
public string searchCategory {
get {
return searchCategoryDropDownList.SelectedValue.ToString();
}
}
</script>
<!-- DropDownList -->
<asp:DropDownList id="searchCategoryDropDownList" class="mainText" runat="server" />


---------index.aspx head content----------
<%@ Page Language="C#" Inherits="Index" Src="classes/Index.cs" EnableViewState="false" ContentType="text/html" ResponseEncoding="iso-8859-1" %>

<%@ Register TagPrefix="eComp" TagName="LatestAdditions" Src="LatestAdditions.ascx" %>
<%@ Register TagPrefix="eComp" TagName="MostPopular" Src="MostPopular.ascx" %>
<%@ Register TagPrefix="eComp" TagName="SearchCategory" Src="SearchCategory.ascx" %>
<%@ Register TagPrefix="eComp" TagName="SearchTransfer" Src="SearchTransfer.ascx" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>eComp.com .:. Music Compilations Cre8ted By U</title>
<script language="JavaScript1.2" src="scripts/navbar.js"></script>
<script language="JavaScript1.2" src="scripts/mm_menu.js"></script>
<link rel="stylesheet" href="styles/styles.css" />
<script runat="server" language="c#">
public void CollectSearchParams(Object s, EventArgs e) {
//st is another user control that takes the values of passed and stores them in the session
st.Search(searchQueryTextBox.Text, sc.searchCategory);
}
</script>
---------index.aspx button click -----------
<td><asp:Button CssClass="mainText" OnClick="CollectSearchParams" Text="Search" runat="server" />
<eComp:SearchTransfer id="st" runat="server" />
</td>
------st--------------------
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<script runat="server" language="c#">
public void Search(string searchQuery, string searchCategory) {
Session["searchQuery"] = searchQuery;
Session["searchCategory"] = searchCategory;
Response.Redirect("search.aspx");
}
</script>
0
davprit
2/26/2005 5:08:05 AM
asp.net.web-forms 93655 articles. 5 followers. Follow

6 Replies
2543 Views

Similar Articles

[PageSpeed] 44


<eComp:SearchTransfer id="st" runat="server" />
shouldn't be
<eComp:SearchCategory id="sc" runat="server" /> ?
because of this
st.Search(searchQueryTextBox.Text, sc.searchCategory);
(double check this line of code)

Hope this helps.

Rules at work:
1) Boss is always right
2) If Boss is wrong; refer rule #1
0
dotnetrook
2/26/2005 11:44:55 PM

Thanks for reply ... it is much appreciated but I don't understand!
<eComp:SearchCategory id="sc" runat="server" /> 
is my User control DropDownList so I am using it's ID (sc) to call the function searchCategory which is defined in sc (see code below). Can you please expand. Thanks
<%@ Import Namespace="System.Data.SqlClient" %>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<script runat="server" language="c#">
protected DataSet objDS;
public void Page_Load() {

//Search Category Data Binding from XML File
objDS = new DataSet();
objDS.ReadXml(MapPath("xml/search_category.xml"));
searchCategoryDropDownList.DataSource = objDS;
searchCategoryDropDownList.DataValueField = "Value";
searchCategoryDropDownList.DataTextField = "Name";
searchCategoryDropDownList.DataBind();
objDS.Clear();

}
public string searchCategory {
get {
return searchCategoryDropDownList.SelectedValue.ToString();
}
}

</script>
<!-- Data List -->
<asp:DropDownList id="searchCategoryDropDownList" class="mainText" runat="server" />
0
davprit
2/27/2005 4:21:36 AM
I was saying you had a sorta typo in your code. You didnt have this line (<eComp:SearchCategory id="sc" runat="server" /> ) in your code. Instead you had (<eComp:SearchTransfer id="st" runat="server" />). Get it now? Do you see the difference?


<eComp:SearchTransfer id="st" runat="server" />
shouldn't be
<eComp:SearchCategory id="sc" runat="server" /> ?
because of this
st.Search(searchQueryTextBox.Text, sc.searchCategory);
(double check this line of code)

Rules at work:
1) Boss is always right
2) If Boss is wrong; refer rule #1
0
dotnetrook
2/27/2005 5:14:59 PM
Thanks again but I don't think that is the issue.  I have both lines in my code.

sc is The DropDownlist user control and
st is another user control which contains a function called Search that ads the value of the Textbox and DropDownlist to the session. It is definitely there as it adds the Textbox value to the session ... it just wont pass the selected item in the dropdownlist to the search function (defined in st) ... it only always passes the first field of the dropddown list.
I think the problem has something to do with the order the page loads?! or I am not understanding the way user controls operate. I reckon that I inderstand the basics of ASP.NET but for proper application development user and custom controls are the key. I need to get my head around writing controls that use code behind, what they inherit from/abstract etc, ways to reference their properties and methods and ways to write methods in user/custom controls.
Does anyone know of a good free resource on the net that details user controls and custom controls from basics to more advanced in C#?
0
davprit
2/28/2005 1:58:53 AM
Hi...

It looks like you're databinding the list each time you load the page/control. This means that even if you have ViewState enabled, the selected value will be wiped out before you can grab it. Put your databinding code inside a check for !Page.IsPostBack and you should be fine.
For what it's worth, ELB doesn't require any contortions like these; it'll even remember your selections without ViewState (and that's the end of my sales pitch for now :) )
Cheers,

Peter Brunone
MS MVP, ASP.NET
Founder, EasyListBox.com
Do the impossible, and go home early.
0
PeterBrunone
2/28/2005 8:49:15 PM
Thanks a million PeterBrunone, 

That more or less fixed it. I added PostBack check and enabled view state for the DropDown list and it all works fine. PostBack is a powerful concept for such a small line of code!!!
0
davprit
3/2/2005 11:31:57 AM
Reply:

Similar Artilces:

Getting the Selected Item of dropdownlist inside Web User Control on a Web Form
Ive got a dropdownlist control inside a web user control called Entity.ascx. This web user control is on a webform.aspx. In Entity.ascx class I created a SelectedEntity property that returns the selected item in the dropdownlist. Inside webform.aspx when btnGo is pushed I set a string and pass it in the url. I am trying to get the entity they selected via the property (SelectedEntity) inside Entity.ascx. As the SelectedEntity property tries to return the selected item in the dropdownlist I get this error: System.NullReferenceException: Object reference not set to an instance...

Pass Values from a user control to a web form
Hi All,  I am currently trying to add captcha to my webform. I have a question on how to pass a number/string from a .ascx to a .aspx page. The aspx is being used in the .ascx (user control) in an image tag. <asp:Image ID="imgCaptcha" runat="server" ImageUrl="Image.aspx"/> The aspx page is being rendered as a jpeg image. So Inorder for the captcha to be displayed with the image, I need to pass the code from the user control to the aspx page. I have an option to pass the number as a query string or use it in session. But is there any ot...

Pass data from Web User Control to Web Form
I have a Web Form that contains a Web User Control. The WUC displays dynamic content. I want to change the TITLE property of the Web Form, based on the contents of the WUC. For example, if the WUC displays information about Horses, I want to change the page title to "HORSES" by passing the string to the parent Web Form. I have tried playing with parameters and such, but I can't remember how I did this in the past. PLEASE HELP!~o0 Spin-Monkey Oo~ The best way to do this is by creating a public property on your web user control and accessing that from your web form. Check ...

Retreiving a value from a web form within a web user control
Hi  I have a page (web form) that retreives some data from a database. To be more specific: at some point when user clicks a button (in the web form) there is some ID number retreived from a database in code behind. At the same time the Visible property of the nestet web user control is chamged to true. I want than forward the ID to the web user control so that a grid view can load data from a database for that ID. How can I access that data (the ID) within a web user control context nested in that page?  Kind regards   Check this ;ink  http://www.codeproject.com/K...

how can i Fill the controls on web page by selecting value from dropdownlist control.
  Hi,  Currentlly i am working on a web application where i require to fill the web form with the selected item in a text box. for example i have dropdown control named supplier_name, and i want to fill all the other controls values from database on the form when i select name from that supplier_name box,i.e , if i select name1, then related to that name, its code,address ,city should appear on related text boxes. I have done the same in windows application with c# , but the problem with web application(asp.net) is that, when i select Supplier _ it...

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++)        {       &...

How to Pass data to pop up form, allow user to add new value, pass new value back to form to do Insert
I have a grid view that shows the user the last meter readings (hours) for several generators. The meter readings need to be added daily.  I would like the user to be able to select the meter record from the grid view and have a pop up javascript form open that would allow the user to enter a new meter reading. Then after I do validation, do an insert of the new reading to the database. Is that a reasonable way of doing what I want? If not, can you give me a suggestion as to how to do it differently. Thanks. Hi..   Instead of opening window to ente...

Passing Values from a Web Form to Another Web Form
Hello All! I am trying to pass values from one web form to another web form. I know that there are 3 ways of doing this: queryString, Server.Transfer and Session. I am using the Server.Transfer method. But I am not able to create, in my 2nd web form, an instance of my 1st web form. My 1st Web form is named CallTrack.aspx and my 2nd is named Export.aspx. What I mean is something like this: Public value as CallTrack. I can't create it in my 2nd web form because when the intellisense is displayed, there's no CallTrack in the options. Thanks!   How about using cross-...

when loading a previously created record on to form, some controls are missing values(controls are depended on values selected in other controls)
Hello - I have created a page for Editing records.  this page will open up a chosen record and allow user to edit the data.On the form, I have 3 drop down lists.   The second dropdown list should fill values depending on value chosen in first dropdown list.  The third dropdown list should show/fill values depending on value chosen in second dropdown list.So taking this into count, i have several records with various data.  When I open-up/load a record in Edit form, only the first dropdown list has a value selected that was the pre-existing va...

Pass value from one User Control to another User Control
I have tried to pass value from one user control to another user control. Because of Page Auto Postback, Contrls are load before page is loaded. So I get the value in 2nd UC after one more post back operation. I have visited many suggessions but I cant solve this. Is anyone can help me to solve this. Thank U mfhossain@gmail.com Muhmmad Fakhrul HossainEmail: mfhossain@gmail.comPhone: +88 01715 111512Web: http://www.mfhossain.info You'd have to do that through the parent probably in it's Page_Load event handler.   userControl1.publicProperty = userControl2.publicProperty;  ...

Passing Values to Web User Controls.
I want to dynamically add web user controls o my page.For that purpose I use LoadControl Method.Now in some of the controls i want to send values of varible from parent web form butI am not able to do so...Can any one help me out with this ???-  ...

Web User Control to Web User Control...
Hi, I have 2 User controls on a page and want Control1 to call a method of Control2. Is this Possible? Example: Con1 = Datalist showing products, each with a Quantity Box and a Button. Con2 = Repeater showing Cart Preview (name, Price) in page.aspx. When I click on the button on the DataList in Con1 it adds the item into the Session based Cart. However it does not update the Cart Preview. I need to call BindPreview() in Con2 in order to update the Cart Preview... Does that make sense? argh! any help much appreciated! PeteWeb Design Nottingham, UK Well I can call BindPreview() from m...

How to pass value to Web User Control
Hi all, I want to pass value to web user control, how can I do that.  I tried to using with property, but failed. Code is like ASPX: WUC objWUC= new WUC(); objWUC.MasterId= 2;   ASCX: public int _MasterID; property int MasterId { get { return _MasterId; } set { _MasterId= Value; } } IN Page_Load(): response.write(this.MasterId)   But it shows 0 (zero).  How can I pass value from aspx to ascx.  I want do some validation based on that.  Please help me, it is very urgent...   Regards, Maxi  Maxi I am not sure if my answer is the...

Passing Value Between Web User Controls
 Hi, I want pass values between web user controls without writing any code to the main page which user controls are put on. I do something like that but after doing that I need to click double to pass the value. The example of what I've done : Department User Control (Code-Behind)  protected void Page_Load(object sender, EventArgs e) { int productId = ProductUserControl.selectedProductId; ... doing some bind work with productId } Product User Control    public static int selectedProductId; protected void Pa...

Web resources about - User Control DropDownList Selected Value Not Passed - asp.net.web-forms

Tag Synonyms - Stack Overflow
Q&A for professional and enthusiast programmers

Accidental entities - what about the UI?
This post is a follow-up to my previous blog post " Accidental entities - you don't need that identity ". In that post, we followed a consultant ...

Flash Builder Plug-in for SAP Netweaver Gateway - Adobe Labs
Search Navigation Labs Home Wiki Home Technologies Alchemy Blueprint Camera Profiles and DNG Profile Editor Cirrus ColdFusion 10 DNG Codec Fireworks ...

Air Astana - Join Now
Thank you for considering membership of Nomad Club – Kazakhstan’s first Frequent Flyer Program. You could soon be on your way to earning free ...

Languages -> C# Articles, Tutorials, Examples: ASP Alliance
.NET,ASP,ASP.NET,SQL,XML,HTML,ADO,ADO.NET,JavaScript,JScript,CSharp,VBScript and VB tutorials from AspAlliance.

Blog - Avisra
Avisra Web Development Home Blog Services Contact The Blog Latest Module Builder: How can we make it better? Sitefinity by Chris on July 2, 2013 ...

Online Booking Tool Support
This Online Booking Tool Support page might help you as you navigate through the process of booking travel through your OBT provided by CWT. ...

@Html and beyond
... ); } return string .Format( “{0}{1}” , me.Member.Name, id); } The Html building methods are quite simple. Building a dropdownlist for a ...

Top Ranked Articles
Top Ranked Articles - Free source code and tutorials for Software developers and Architects.; Updated: 23 Feb 2013

Unit Testing DateTime.Now Without Isolation
public virtual void SeedWithYearsSince(DropDownList list, int year){ for (int index = year; index

Resources last updated: 1/9/2016 1:28:51 PM