how to get values in dropdownlist bounded within a gridview?

Total Post:119

 2077  View(s)
Rate this:

Inside gridview a dropdownlist is there 

<asp:TemplateField HeaderText="Quantity">
        <asp:DropDownList ID="quantity" runat="server" DataValueField="ItemID" DataTextField="Quantity">

for each itemid there is some numeric value in Quantity field of Database Table i want that this dropdown must contain the values from 1 to quantity.DataTextField for all the items present in the cart 

the procedure by which gridview is bound is 

create proc [dbo].[prcItemsinCart](@CartID int)
    select distinct ct.Price,ct.Quantity,ct.ItemID,
           isnull((  select top 1 convert(varchar,PhotoID,10) + '.' + ExtName
                 from ProductPhoto
                 where ProductID = ct.ProductID ),'NoImage.jpg'
           ) as Product,
           ( Select Price*Quantity
             from CartItems
             where CartID=ct.CartID and ProductID=ct.ProductID
           ) as SubTotal
    from CartItems as ct
    inner join ProductInfo as p on ct.ProductID=p.ProductID
    inner join ProductPhoto as pp on ct.ProductID=pp.ProductID
    where ct.CartID=@CartID
  1. Post:378

    Re: how to get values in dropdownlist bounded within a gridview?

    Hi Goti, 

    I would add a HiddenField in the TemplateField to hold the CartID, I will use the CartID in the code. My Markup should look like: 

    <asp:TemplateField HeaderText="Quantity">
            <asp:HiddenField ID="hdnId" runat="server" value='<%#Eval("CartID") %>'></asp:HiddenField>                           
            <asp:DropDownList ID="quantity" runat="server" DataValueField="ItemID" DataTextField="Quantity">

    In the code, in GridView's RowDataBound I am finding the DropDownList and HiddenField, running a Sql Query to bring my expected data, and binding them to my DropdownList: 

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            DropDownList quantity = e.Row.FindControl("quantity") as DropDownList;
            HiddenField hdnId = e.Row.FindControl("hdnId") as HiddenField;
            if (quantity != null && hdnId != null)
                string queryString = String.Format("SELECT ItemID, Quantity FROM  CartItems  WHERE CartID= {0}", hdnId.Value);
                //MyConnectionString is your connection string in web.config
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
                    SqlCommand command = new SqlCommand(queryString, connection);
                    SqlDataReader reader = command.ExecuteReader();
                    quantity.DataSource = reader;
                    quantity.DataValueField = "ItemID";
                    quantity.DataTextField = "Quantity";

      Modified On Apr-06-2018 11:28:19 PM