Solved

Populating a DropDownList with comma separted data in a single column in a sql table.

Posted on 2004-03-25
14
304 Views
Last Modified: 2008-02-01
I need to get data to fill a sizes drop down list. The data is in a single  column "sizes" in table "Products". And the data takes the following form and is a of type nvarchar (10):

Either   23,24,25,26,26,28,29,30    or    One Size  or  S,M,L,XL.

Thanks for the help, in advance.

Derek
0
Comment
Question by:dbruyere
  • 5
  • 5
  • 2
  • +1
14 Comments
 
LVL 7

Expert Comment

by:ramesh12
ID: 10681177
get that field and split it based on ","

strValues=split(recordset(fieldname),",")

Add these using for loop like

for i=0 to ubound(strvalues)
--Your adding code goes here
next
0
 
LVL 12

Expert Comment

by:venkateshwarr
ID: 10681201

<%
Dim strPaco
strPaco = "23,24,25,26,26,28,29,30"

arrPaco = Split(strPaco,",")

Response.write "<select>"
For i =  LBound(arrPaco)  to  UBound(arrPaco)

Response.write "<option value= " & arrPaco &" >"

Next
Response.write "</select>"

%>

0
 
LVL 12

Expert Comment

by:venkateshwarr
ID: 10681217

Sorry ramesh... did not see ur post
0
 
LVL 7

Expert Comment

by:ramesh12
ID: 10681342
No problem venkatesh.
0
 
LVL 14

Accepted Solution

by:
dfu23 earned 150 total points
ID: 10681808
C# example ... assuming a DropDownList web control ddlSizes named exists:

string[] sizes = "23,24,25,26,26,28,29,30".Split(',');
for (int i = 0; i < sizes.Length; i++)
{
    ddlSizes.Items.Add(new ListItem(sizes[i], sizes[i]));
}
0
 
LVL 14

Expert Comment

by:dfu23
ID: 10681847
Oh yeah ... you are pulling the sizes in from the DB ... from maybe a DataReader (call it, dr)?

// I am using index zero ... change to whatever needed
string data = dr[0]["sizes"].ToString();
string[] sizes = data.Split(',');
...
0
 
LVL 1

Author Comment

by:dbruyere
ID: 10682701
Thanks for all your posts. I'm a new programmer and this is huge help. Here is what I've tried and the problem I am having:

string data = myProductDetails.Sizes.ToString();
string[] Sizes = data.Split(',');

for (int i = 0; i < Sizes.Length; i++)
 {
    ddlSizes.Items.Add(new ListItem(Sizes[i], Sizes[i]));
 }

addToCart.NavigateUrl = String.Format("AddToCart.aspx?ProductID={0}&Sizes={1}", ProductID, ddlSizes.SelectedItem);

The problem I am having is that the nav url is only showing the top choice from the ddlSizes. It does not change when the choice is made. I have tried setting ddlSizes AutoPostBack to True and all that did was when you mada a choice, the postback caused the ddl to repopulate and so your choice would be the default in the ddl. Is there something I am missing?

Here is the url so that you can see what I am trying to do.

http://63.196.244.194/paypalcommerce/ProductDetails.aspx?productID=409

Thankyou,
Derek
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 14

Expert Comment

by:dfu23
ID: 10683992
I would imagine that you are setting up the DropDownList in the Page_Load, right?
Are you doing a:

if (!Page.IsPostBack) {
   // Initialize your form elements here
   // This "if" ensures that the form is only initialized when navigated to ... and not re-initialized when data is posted back to it ...
}

Try setting the AutoPostBack for the ddl to true and set the NavigateUrl in the event handler for the OnChange event of the ddl ...
0
 
LVL 1

Author Comment

by:dbruyere
ID: 10684110
Here is the page in question. I am not sure how to do what you are saying exactly. I tried the if(!Page.IsPostBack), but I didn't do it right and got an error.

 public ProductDetailsPage() {
            Page.Init += new System.EventHandler(Page_Init);

            }

        //*******************************************************
        //
        // The Page_Load event on this page is used to obtain
        // product information from a database and then update
        // UI elements with them.
        //
        // Note that this page is output cached at 1 minute
        // intervals.  This eliminates the need to hit the database
        // on each request to the page.
        //
        //*******************************************************

        private void Page_Load(object sender, System.EventArgs e) {

            // Obtain ProductID from QueryString
            int ProductID = Int32.Parse(Request.Params["ProductID"]);

                  // Obtain Product Details
            ASPNET.StarterKit.Commerce.ProductsDB products = new ASPNET.StarterKit.Commerce.ProductsDB();
            ASPNET.StarterKit.Commerce.ProductDetails myProductDetails = products.GetProductDetails(ProductID);
                  
            // Update Controls with Product Details
            desc.Text = myProductDetails.Description;
                  //sizes.Text = myProductDetails.Sizes;
            UnitCost.Text = String.Format("{0:c}", myProductDetails.UnitCost);
            ModelName.Text = myProductDetails.ModelName;
            ModelNumber.Text = myProductDetails.ModelNumber.ToString();
            ProductImage.ImageUrl = "ProductImages/" + myProductDetails.ProductImage;
                  AlsoBoughtList.ProductID = ProductID;
           
                  // Populate the Drop Down List with size choices
                  string data = myProductDetails.Sizes.ToString();
                  string[] Sizes = data.Split(',');

                  for (int i = 0; i < Sizes.Length; i++)
                   {
                    ddlSizes.Items.Add(new ListItem(Sizes[i], Sizes[i]));
                   }

                  addToCart.NavigateUrl = String.Format("AddToCart.aspx?ProductID={0}&Sizes={1}", ProductID, ddlSizes.SelectedItem);
                  
        }

        private void Page_Init(object sender, EventArgs e)
{
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
        }

            #region Web Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            /// <summary>
            /// Returns a <see cref="PayPal.Web.Controls.CustomerInfo"/> associated with
            /// the currently logged on user. If the user has not logged in or the customer
            /// information does not exist, returns NULL.
            /// </summary>
            /// <returns>Returns the <see cref="PayPal.Web.Controls.CustomerInfo"/> associated with the user or NULL if none exists.</returns>
            private CustomerInfo GetCustomerInfo()
            {
                  string customerID = User.Identity.Name;

                  if (customerID == string.Empty)
                  {
                        return null;
                  }
                  else
                  {
                        CustomerDetails cd = new CustomersDB().GetCustomerDetails(customerID);
                        return new PayPal.Web.Controls.CustomerInfo(cd.FirstName, cd.LastName, cd.Address1, cd.Address2,
                              cd.City, cd.State, cd.Zip, cd.NightPhoneA, cd.NightPhoneB, cd.NightPhoneC,
                              cd.DayPhoneA, cd.DayPhoneB, cd.DayPhoneC);
                  }
            }
0
 
LVL 14

Expert Comment

by:dfu23
ID: 10687304
private void Page_Load(object sender, System.EventArgs e) {
    if (!Page.IsPostBack) { // Ensuring page is only initialized once
        ... // Your code here
    }
}

That's the common usage of the IsPostBack property ...

It appears that you are using VS.NET ... in the design view of the page select the ddl and in the Properties Window set AutoPostBack to True ... then double-click the ddl which should jump you over to the Code Behind and into an event handler for the OnChange event of the ddl

Once there try something like what you have done before:

int ProductID = Int32.Parse(Request.Params["ProductID"]);
addToCart.NavigateUrl = String.Format("AddToCart.aspx?ProductID={0}&Sizes={1}", ProductID, ddlSizes.SelectedItem);
0
 
LVL 1

Author Comment

by:dbruyere
ID: 10688380
That's exactly what I did. I get the following errror. I get the error when I make the choice selection.

Server Error in '/PayPalCommerce' Application.
--------------------------------------------------------------------------------

Value cannot be null. Parameter name: String
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.ArgumentNullException: Value cannot be null. Parameter name: String

Source Error:


Line 134:            private void ddlSizes_SelectedIndexChanged(object sender, System.EventArgs e)
Line 135:            {
Line 136:               int ProductID = Int32.Parse(Request.Params["ProductID"]);      
Line 137:               addToCart.NavigateUrl = String.Format("AddToCart.aspx?ProductID={0}&Sizes={1}", ProductID, ddlSizes.SelectedItem);
Line 138:            }
 

Source File: c:\program files\paypal\asp.net commerce starter kit for paypal\paypalcommerce\productdetails.aspx.cs    Line: 136

Stack Trace:


[ArgumentNullException: Value cannot be null.
Parameter name: String]
   System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +0
   System.Int32.Parse(String s) +38
   ASPNET.StarterKit.Commerce.ProductDetailsPage.ddlSizes_SelectedIndexChanged(Object sender, EventArgs e) in c:\program files\paypal\asp.net commerce starter kit for paypal\paypalcommerce\productdetails.aspx.cs:136
   System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e) +108
   System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +26
   System.Web.UI.Page.RaiseChangedEvents() +115
   System.Web.UI.Page.ProcessRequestMain() +1081

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573
0
 
LVL 1

Author Comment

by:dbruyere
ID: 10688419
The <form> was set to method=get. I'm not sure if that makes a difference, but when I set it to post, and select a size, the page comes back empty.
0
 
LVL 14

Expert Comment

by:dfu23
ID: 10689989
in your statement:

addToCart.NavigateUrl = String.Format("AddToCart.aspx?ProductID={0}&Sizes={1}", ProductID, ddlSizes.SelectedItem);

I think that the Value or Text needs to be added for the ddlSizes.SelectedItem:

ddlSizes.SelectedItem.Value

or

ddlSizes.SelectedItem.Text

It looks like you should keep the Method as GET instead of POST ...
0
 
LVL 1

Author Comment

by:dbruyere
ID: 10690986
I have tried that as well. It doesn't seem to effect it one way or the other. The problem is when I do select the size, I get that error from the post above. Here is what I have. If you have a moment, go the this link and see what happens when you select a size:  http://63.196.244.194/paypalcommerce/ProductDetails.aspx?productID=409

 public class ProductDetailsPage : System.Web.UI.Page {

        protected System.Web.UI.WebControls.Label ModelName;
        protected System.Web.UI.WebControls.Image ProductImage;
        protected System.Web.UI.WebControls.Label desc;
            //protected System.Web.UI.WebControls.DropDownList ddlSizes;
            protected System.Web.UI.HtmlControls.HtmlForm form1;
            protected System.Web.UI.WebControls.Image Image1;
            protected System.Web.UI.WebControls.HyperLink addToCart;
            protected System.Web.UI.WebControls.Label ModelNumber;
            protected System.Web.UI.WebControls.Label UnitCost;
            protected System.Web.UI.WebControls.Image Image2;
            protected System.Web.UI.WebControls.Image Image3;
            protected System.Web.UI.WebControls.Image Image4;
            protected System.Web.UI.WebControls.HyperLink HyperLink1;
            protected System.Web.UI.WebControls.Image Image6;
            protected System.Web.UI.WebControls.Image Image7;
            protected System.Web.UI.WebControls.DropDownList ddlSizes;
            protected C_AlsoBought AlsoBoughtList;    
       
            
 
        public ProductDetailsPage() {                  
                        Page.Init += new System.EventHandler(Page_Init);                        
            }

        //*******************************************************
        //
        // The Page_Load event on this page is used to obtain
        // product information from a database and then update
        // UI elements with them.
        //
        // Note that this page is output cached at 1 minute
        // intervals.  This eliminates the need to hit the database
        // on each request to the page.
        //
        //*******************************************************

        private void Page_Load(object sender, System.EventArgs e) {


                  if (!Page.IsPostBack)
                  {
                  
                        // Obtain ProductID from QueryString
                        int ProductID = Int32.Parse(Request.Params["ProductID"]);      
                        
                        // Obtain Product Details
                        ASPNET.StarterKit.Commerce.ProductsDB products = new ASPNET.StarterKit.Commerce.ProductsDB();
                        ASPNET.StarterKit.Commerce.ProductDetails myProductDetails = products.GetProductDetails(ProductID);
                  
                  
                        // Update Controls with Product Details
                        desc.Text = myProductDetails.Description;
                        //sizes.Text = myProductDetails.Sizes;
                        UnitCost.Text = String.Format("{0:c}", myProductDetails.UnitCost);
                        ModelName.Text = myProductDetails.ModelName;
                        ModelNumber.Text = myProductDetails.ModelNumber.ToString();
                        ProductImage.ImageUrl = "ProductImages/" + myProductDetails.ProductImage;
                        AlsoBoughtList.ProductID = ProductID;

                          
                        // Populate the Drop Down List with size choices
                        string data = myProductDetails.Sizes.ToString();
                        string[] Sizes = data.Split(',');

                        for (int i = 0; i < Sizes.Length; i++)
                        {
                              ddlSizes.Items.Add(new ListItem(Sizes[i], Sizes[i]));
                        }
                  
                  }
        }

        private void Page_Init(object sender, EventArgs e)
{
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
        }

            #region Web Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
                  this.ddlSizes.SelectedIndexChanged += new System.EventHandler(this.ddlSizes_SelectedIndexChanged);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            /// <summary>
            /// Returns a <see cref="PayPal.Web.Controls.CustomerInfo"/> associated with
            /// the currently logged on user. If the user has not logged in or the customer
            /// information does not exist, returns NULL.
            /// </summary>
            /// <returns>Returns the <see cref="PayPal.Web.Controls.CustomerInfo"/> associated with the user or NULL if none exists.</returns>
            private CustomerInfo GetCustomerInfo()
            {
                  string customerID = User.Identity.Name;

                  if (customerID == string.Empty)
                  {
                        return null;
                  }
                  else
                  {
                        CustomerDetails cd = new CustomersDB().GetCustomerDetails(customerID);
                        return new PayPal.Web.Controls.CustomerInfo(cd.FirstName, cd.LastName, cd.Address1, cd.Address2,
                              cd.City, cd.State, cd.Zip, cd.NightPhoneA, cd.NightPhoneB, cd.NightPhoneC,
                              cd.DayPhoneA, cd.DayPhoneB, cd.DayPhoneC);
                  }
            }

            private void ddlSizes_SelectedIndexChanged(object sender, System.EventArgs e)
            {      
                  // Obtain ProductID from QueryString
                  int ProductID = Int32.Parse(Request.Params["ProductID"]);

                  addToCart.NavigateUrl = String.Format("AddToCart.aspx?ProductID={0}&Sizes={1}", ProductID, ddlSizes.SelectedItem.Text);
            }

            
                    
     
    }
}
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

I've been asked to discuss some of the UX activities that I'm using with my team. Here I will share some details about how we approach UX projects.
Any business that wants to seriously grow needs to keep the needs and desires of an international audience of their websites in mind. Making a website friendly to international users isn’t prohibitively expensive and can provide an incredible return…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now