Link to home
Start Free TrialLog in
Avatar of dbruyere
dbruyere

asked on

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

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
Avatar of ramesh12
ramesh12

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

<%
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>"

%>


Sorry ramesh... did not see ur post
No problem venkatesh.
ASKER CERTIFIED SOLUTION
Avatar of dfu23
dfu23

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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(',');
...
Avatar of dbruyere

ASKER

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

            
                    
     
    }
}