Solved

how to display a Drop Down List in a GridView

Posted on 2008-10-01
5
797 Views
Last Modified: 2013-11-07
Hello All,

i have a gridview with columns like ItemNo, Title, Price, Size. everything is coming from SQL DB. what i am trying to do is to display a DDL in the gridview so that both the price and Size are diplayed in a DDL format. to explain clearly right now for every itemno, i have different sizes namely 1,2,3,4,5 etc and a different price according to the sizes. for example

itemno     title                  price        size

A1001   Red Shoes         $15           2
A1001  Red Shoes          $20           4

A1002 Black Shoes          $25           7    
A1002  Black Shoes          $35        10  and so on.

as you can see its displaying the title and itemno so many items. i was wondering if there's way to just display itemno and title ( just once ) and their respective prices and sizes in a DDL's. something

like below.

itemNo          title              price     size

A1001           Red Shoes     $15      2
                                         $20       4

A1002     Black Shoes    $25       7
                                         $35     10
so basically i want to display the sizes and prices like above. i am not sure if how to do this and
doesnt know if DDL is the correct option to achieve this.
PLEASE Kindly advice me.
i am attaching my full code.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GVsearch.aspx.cs" Inherits="GVsearch" %>
 
<!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 runat="server">
    <title>   </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox id="txtSearch" runat="server" />
 
<asp:Button id="btnSearch" runat="server"
    Text    = "Search"
    OnClick = "btnSearch_OnClick" />
    <br />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:LocalDBConnectionString %>"
            SelectCommand="SELECT [ItemNumber], [Title], [Price], [SizeName],[Description],[ShortTitle],[ShortDescription] FROM [SearchTable] WHERE (([Title] LIKE '%' + replace(@Title, ' ', '%') + '%') OR ([ShortDescription] LIKE '%' + replace(@ShortDescription, ' ', '%') + '%') OR ([ShortTitle] LIKE '%' + replace(@ShortTitle, ' ', '%') + '%') OR ([Description] LIKE '%' + replace(@Description, ' ', '%') + '%') OR ([ItemNumber] LIKE '%' + replace(@ItemNumber, ' ', '%') + '%') OR ([SizeName] LIKE '%' + replace(@SizeName, ' ', '%') + '%'))" OnSelecting="SqlDataSource1_Selecting" >
            <SelectParameters>
                <asp:Parameter  Name="Title"  Type="String" />
                <asp:Parameter  Name="ShortDescription" Type="String" />
                <asp:Parameter  Name="ShortTitle" Type="String" />
                <asp:Parameter  Name="Description" Type="String" />
                <asp:Parameter  Name="ItemNumber"  Type="String" />
                <asp:Parameter  Name="SizeName" Type="String" />
            </SelectParameters>
        </asp:SqlDataSource>
    <br />
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="ItemNumber" DataSourceID="SqlDataSource1" ForeColor="#333333"
            GridLines="None" AllowSorting="True">
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="ItemNumber" HeaderText="Item" InsertVisible="False"
                    SortExpression="ItemNumber" HtmlEncode="False" />
                <asp:BoundField DataField="Title" HeaderText="Product Name" SortExpression="Title" HtmlEncode="False" />
                <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price"  DataFormatString="{0:c}" HtmlEncode="False" />
                <asp:BoundField DataField="SizeName" HeaderText="Size" SortExpression="SizeName"  HtmlEncode="False" />
                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" HtmlEncode="False" />
                            </Columns>
            <RowStyle BackColor="#E3EAEB" />
            <EditRowStyle BackColor="#7C6F57" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
  </div>
    
    </form>
</body>
</html>
 
------------------CODE BEHIND---------
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
public partial class GVsearch : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    protected void btnSearch_OnClick(object sender, EventArgs e)
    {
        GridView1.DataBind();
    }
 
 
 
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        e.Command.Parameters["@Title"].Value = txtSearch.Text;
        e.Command.Parameters["@ShortDescription"].Value = txtSearch.Text;
        e.Command.Parameters["@ShortTitle"].Value = txtSearch.Text;
        e.Command.Parameters["@Description"].Value = txtSearch.Text;
        e.Command.Parameters["@ItemNumber"].Value = txtSearch.Text;
        e.Command.Parameters["@SizeName"].Value = txtSearch.Text;
           }
 
}

Open in new window

0
Comment
Question by:niceoneishere
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
5 Comments
 
LVL 4

Expert Comment

by:Joni Kettunen
ID: 22621811
0
 
LVL 1

Author Comment

by:niceoneishere
ID: 22627066
Hello Sir,
all i am trying to do is for every ItemNo in the gridview i want to display that itemno's sizes in a DropDownList.

i have modified my code according to link 1 you have posted and here is my new code. it still doesnt work.
can you please help me out sir, i appreciate it.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Dgsearch.aspx.cs" Inherits="Dgsearch" %>
 
<!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 runat="server">
    <title>My SQL Search Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox id="txtSearch" runat="server" />
 
<asp:Button id="btnSearch" runat="server"
    Text    = "Search"
    OnClick = "btnSearch_OnClick" />
<br />
<asp:GridView ID="GridView1" runat="server" 
        AutoGenerateColumns="false" DataKeyNames="ItemNumber">
        <Columns>
        <asp:TemplateField HeaderText="Item Number">
        <ItemTemplate>
        <%# DataBinder.Eval(Container.DataItem, "ItemNumber") %>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Product Name">
        <ItemTemplate>
        <!--<asp:Label ID="lbgvtitle" runat="server" Text='<%# Eval("Title") %>' />-->
        <%# DataBinder.Eval(Container.DataItem, "Title") %>
         </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Available Sizes">
            <ItemTemplate>
            <asp:DropDownList ID="ddlSizes" runat="server">
            </asp:DropDownList>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Price">
        <ItemTemplate>
        <%# DataBinder.Eval(Container.DataItem, "Price") %>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText=" Description">
        <ItemTemplate>
        <%# DataBinder.Eval(Container.DataItem, "Description") %>
        </ItemTemplate>
        </asp:TemplateField>       
        </Columns>
        </asp:GridView>
 
 
    </div>
    </form>
</body>
</html>
-------------------CODE BEHIND--------------------------------
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
 
public partial class Dgsearch : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    public void btnSearch_OnClick(object sender, EventArgs e)
    {
        SqlConnection objConnection = null;
        SqlCommand objCommand = null;
        SqlDataAdapter objAdapter = null;
        DataSet objDataSet = null;
        string strSearch = null;
        string strSQLQuery = null;
 
        // Get Search 
        strSearch = txtSearch.Text;
 
        // If there's nothing to search for then don't search
        // o/w build our SQL Query and execute it.
        if (strSearch.Trim(' ').Length > 0)
        {
            // Set up our connection.
            objConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["WSLocalDBConnectionString"].ConnectionString);
 
            // Set up our SQL query text.
 
            strSQLQuery = "SELECT ItemNumber, Title, SizeName, Price, Description " + "FROM SearchTable " + "WHERE Title LIKE '%" + strSearch.Replace("'", "''") + "%' " + "ORDER BY ItemNumber;";
            // Create new command object passing it our SQL query
            // and telling it which connection to use.
            objCommand = new SqlCommand(strSQLQuery, objConnection);
 
            // Get a DataSet to bind the DataGrid to
            objAdapter = new SqlDataAdapter(objCommand);
            objDataSet = new DataSet();
            objAdapter.Fill(objDataSet);
 
            GridView1.DataSource = objDataSet;
            GridView1.DataBind();
 
            DropDownList drdSizes;
 
           foreach (GridViewRow gvrows in GridView1.Rows)
            {
                // Nested DropDownList Control reference is passed to the DrdSizes object. This will allow you access the properties of dropdownlist placed inside the GridView Template column.
 
               drdSizes = (DropDownList)(GridView1.Rows[gvrows.RowIndex].Cells[1].FindControl("ddlSizes"));
 
                // DataBinding of nested DropDownList Control for each row of GridView Control.  
 
               drdSizes.DataSource = objDataSet;
                drdSizes.DataValueField = "ItemNumber";
                drdSizes.DataTextField = "SizeName";
                drdSizes.DataBind();
 
                // GridView DataKeys Collection object is used here to set the SelectedValue property of nested DropDownList in each row.
 
                drdSizes.SelectedValue = GridView1.DataKeys[gvrows.RowIndex]["ItemNumber"].ToString();
 
 
            }
 
            objConnection.Close();
        }
        else
        {
            txtSearch.Text = "Enter Search Here";
        }
    }
 
 
}

Open in new window

0
 
LVL 26

Accepted Solution

by:
Anurag Thakur earned 500 total points
ID: 22628584
even in your modified code i cannot see a dropdownlist in the item template for item number
please go through this link and try again. for for giving a link again but these samples are already available on the net so no need to reinvent the wheel
http://www.codeproject.com/KB/dotnet/AccessingControlsInsideGr.aspx
0
 
LVL 4

Expert Comment

by:Joni Kettunen
ID: 22631173
I have to agree with ragi0017. His code sample is better.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

749 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