Search code examples
c#asp.nettrim

Parsing Decimals from a String


I have a dropdownlist on a web form that has an item name and a price associated with it (which is not visible to the user). I am using selecteditem.Text and selectedvalue to capture the item name and the price. To combat duplicate entries for the selectedvalue I am storing entries like so

Signed Cap 10.0
Signed Glove 10.1
Signed Shirt 10.2
Bat Shavings .50
Hat Brim .50

Then parsing it out by using the below

String[] str = dropdownlist1.SelectedValue.ToString().Split('.');
String itemprice = str[0].Trim();

My syntax works great, EXCEPT for the decimal values! On Bat Shavings and Hat Brim I need to retain the decimal value! What should I alter or how should I set up my syntax to allow duplicate selected values or to keep the decimals? I understand that using str[0] is what is causing me to loose the decimals, BUT how can I work around it for the 2 (possibly more in the future) scenarios where they need to be remain in tact?


Solution

  • Its hard to tell from your posting how your getting your data, but I would load my data from the database into a data object, then bind that object to the drop down list.

    Here is the Inventory Class I used to store the data from the database:

    public class Inventory
    {
        public int ProductID { get; set; }
        public string ProductDescription { get; set; }
        public decimal ProductPrice { get; set; }
    
        public Inventory(int ID, string Description, decimal Price)
        {
            this.ProductID = ID;
            this.ProductDescription = Description;
            this.ProductPrice = Price;
        }
    
        public string DDLValue
        {
            get
            {
                return string.Format("{0}|{1}|{2}", ProductID, ProductDescription, ProductPrice);
            }
        }
    
        public string DDLText
        {
            get
            {
                return string.Format("{0} [{1}]", ProductDescription, ProductPrice.ToString("C"));
            }
        }
    }
    

    Here is a sample of how to configure the page control:

    <asp:DropDownList ID="ddlProducts" runat="server" DataValueField="DDLValue" DataTextField="DDLText" />
    

    In the page code behind, load your data into the drop down:

    protected void LoadProductsFromDatabase()
        {
            System.Collections.Generic.List<Inventory> My_DDL_Datasource = new System.Collections.Generic.List<Inventory>();
    
            // write your code to pull database values
            // populating list with sample data for stackoverflow
            // make sure to use a replace statement to remove any delimiter characters that may be in the description
            My_DDL_Datasource.Add(new Inventory(1, "Product 1".Replace("|", ""), 0.50m));
            My_DDL_Datasource.Add(new Inventory(2, "Product 2".Replace("|", ""), 1.50m));
            My_DDL_Datasource.Add(new Inventory(3, "Product 3".Replace("|", ""), 0.50m));
            My_DDL_Datasource.Add(new Inventory(4, "Product 4".Replace("|", ""), 10.50m));
    
            ddlProducts.DataSource = My_DDL_Datasource;
            ddlProducts.DataBind();
        }
    

    In the page code behind, create a method to get your drop down list selected value:

    protected Inventory GetSelectedProduct()
        {
            try
            {
                if (ddlProducts.Items.Count == 0)
                {
                    // do nothing, fall thru will return null
                }
                else
                {
                    string[] DDLValue = ddlProducts.SelectedValue.Split('|');
    
                    int ivalue = 0;
                    int.TryParse(DDLValue.GetValue(0).ToString(), out ivalue);
    
                    decimal dvalue = 0.00m;
                    decimal.TryParse(DDLValue.GetValue(2).ToString(), out dvalue);
    
                    // only return object if the productid and product price were successfully parsed.
                    // this logic assumes no products are free
                    if (ivalue > 0 && dvalue > 0.00m)
                    {
                        return new Inventory(ivalue, DDLValue.GetValue(1).ToString(), dvalue);
                    }
                }
            }
            catch { }
            return null;
        }
    

    In the page code behind, do something with your selected value:

    protected void DoSomethingWithValue()
        {
            Inventory MyInventoryItem = GetSelectedProduct();
    
            if (MyInventoryItem != null)
            {
                // selected item successfully parsed
                // do something with it.
    
                Response.Write(
                    string.Format("Your selected product:<br />{0}<br />UniqueID: {1}<br />Price: {2}",
                    Server.HtmlEncode(MyInventoryItem.ProductDescription),
                    MyInventoryItem.ProductID,
                    MyInventoryItem.ProductPrice.ToString("C")
                ));
            }
            else
            {
                // error parsing information stored in drop down list value
            }
        }