About the dropdownlist embedded into Gridview

Last post 02-28-2008 10:20 AM by aamador. 5 replies.

Sort Posts:

  • About the dropdownlist embedded into Gridview

    02-28-2008, 5:07 AM

    I am a newbie.

    Problem Description

    1. One Gridview has "datasourceA" which the table A contains "category_id" (number)

    2. the dropdownlist has "datasourceB" which the table B contains "category_id" (number) and "category_name".

     The display part which makes category_name instead of category_id has been done by joining 2 tables.

    Now the EditTemplate of Gridview contains dropdownlist, how can I do that makes someone choosing dropdownlist item (category_name) and then update the table A category_id ?

     

        <asp:SqlDataSource ID="myDataSource2" runat="server" ConnectionString="server=HOBBSJVPC070\SQLEXPRESS;database=db_book;uid=sa;pwd=23456"
                    DeleteCommand="Update book set status='D' where book_id=@book_id"
                    SelectCommand="Select b.book_id, b.isbn, b.book_name, b.qty_in_stock, b.cost, b.book_img, b.editor_name, b.issue_date, b.purchase_date, c.category_name, b.description, b.qty_sell from book b left outer join category c on b.category_id=c.category_id where b.status='V'"
                    UpdateCommand="Update book set isbn=@isbn, book_name=@book_name, qty_in_stock=@qty_in_stock, cost=@cost, book_img=@book_img, editor_name=@editor_name, category_id=@category_id,description=@description, qty_sell=@qty_sell where book_id=@book_id">
                    <UpdateParameters>
                        <asp:ControlParameter ControlID="ddcategory" PropertyName="SelectedValue" Name="category_id" />
                    </UpdateParameters>
        </asp:SqlDataSource>
       
        <asp:GridView ID="GridView2" runat="server" AllowPaging="true" AllowSorting="true"
                    AlternatingRowStyle-BackColor="#cccccc" AutoGenerateColumns="false" BorderColor="black"
                    CellPadding="4" DataKeyNames="book_id" DataSourceID="myDataSource2" Font-Size="8pt"
                    HeaderStyle-BackColor="#cccc99" RowStyle-BackColor="#ffffff">
                    <Columns>
                        <asp:BoundField DataField="book_id" HeaderText="Book ID" ReadOnly="true" />
                        <asp:BoundField DataField="isbn" HeaderText="ISBN" />
                        <asp:BoundField DataField="book_name" HeaderText="Book Name" />
                        <asp:TemplateField HeaderText="Category">
                            <ItemTemplate>
                                <%#Eval("category_name")%>                       
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="ddcategory" runat="server"  datasourceid="myDataSource3" datatextfield="category_name" datavaluefield="category_id">
                                </asp:DropDownList><asp:SqlDataSource ID="myDataSource3" runat="server" ConnectionString="server=HOBBSJVPC070\SQLEXPRESS;database=db_book;uid=sa;pwd=23456"
                    SelectCommand="Select * from category where status='V'">
        </asp:SqlDataSource>
                            </EditItemTemplate>
                        </asp:TemplateField>
                       
                        <asp:BoundField DataField="qty_in_stock" HeaderText="Stock Qty" />
                        <asp:BoundField DataField="cost" HeaderText="Cost($)" />
                        <asp:BoundField DataField="book_img" HeaderText="Book Image" />
                        <asp:BoundField DataField="editor_name" HeaderText="Editor" />
                        <asp:BoundField DataField="issue_date" HeaderText="Issue Date" />
                        <asp:BoundField DataField="purchase_date" HeaderText="Purchase Date" SortExpression="datatime" DataFormatString="{0:yyyy-MM-dd}" HtmlEncode="false" />
                        <asp:BoundField DataField="description" HeaderText="Description" />
                        <asp:BoundField DataField="qty_sell" HeaderText="Selling Book Qty" />
                        <asp:CommandField ButtonType="Button" HeaderStyle-BackColor="SkyBlue" HeaderText="Edit / Delete"
                            ItemStyle-BackColor="GreenYellow" ItemStyle-Wrap="false" ShowCancelButton="true"
                            ShowDeleteButton="true" ShowEditButton="true" />
                    </Columns>
         </asp:GridView>

     

  • Re: About the dropdownlist embedded into Gridview

    02-28-2008, 7:02 AM
    Answer
    • Participant
      918 point Participant
    • The Eagle
    • Member since 04-30-2007, 1:06 PM
    • Posts 181

    You have to add to your DropDownList:

    SelectedValue = '<%#Bind("category_id")%>'

  • Re: About the dropdownlist embedded into Gridview

    02-28-2008, 7:04 AM
    Answer
    • Member
      371 point Member
    • josephjohn
    • Member since 02-27-2008, 7:10 AM
    • Kozhicode, Kerala
    • Posts 84

    Please see the below example.

    This code comes inside the edit template columns

    <EditItemTemplate>

    <asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"

    DataSourceID="CategoryDataSource" DataTextField="CategoryName" DataValueField="CategoryID"

    SelectedValue='<%# Bind("CategoryID") %>'>

    <asp:ListItem Value=''>Select One</asp:ListItem>

    </asp:DropDownList>&nbsp;

    </EditItemTemplate>

     

     

    Please mark the post as answered if it helped you.
    Filed under:
  • Re: About the dropdownlist embedded into Gridview

    02-28-2008, 7:10 AM
    Answer
    • Contributor
      5,201 point Contributor
    • aamador
    • Member since 02-11-2008, 5:49 PM
    • Posts 1,107

    I noticed you were being ignored so I decided to help you out.

    First let me give a very simple example that works.  It is all declarative so there is only asp markup no code.

    Here we go

     

    Page Language="VB" AutoEventWireup="false" CodeFile="DDLTemplateExample.aspx.vb" Inherits="DDLTemplateExample" %>
    
    <!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>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            This Example uses the Declarative model. Notice that I turned supplier ID into a 
            template field then created a datasource to suppliers table just to populate the 
            data lookup selecting SupplierID and CompanyName for my dropdown value and 
            display text.  Then I bound the the ddl value to the outer datasource 
            SupplierID and I did all of this using the wizard.  Try your luck at 
            setting the Category ID  the datasource should be categories table<br />
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:CommandField ShowEditButton="True" />
                    <asp:BoundField DataField="ProductID" HeaderText="ProductID" 
                        InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
                    <asp:BoundField DataField="ProductName" HeaderText="ProductName" 
                        SortExpression="ProductName" />
                    <asp:TemplateField HeaderText="SupplierID" SortExpression="SupplierID">
                        <EditItemTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server" 
                                DataSourceID="SqlDataSource2" DataTextField="CompanyName" 
                                DataValueField="SupplierID" SelectedValue='<%# Bind("SupplierID") %>'>
                            </asp:DropDownList>
                            <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
                                ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
                                SelectCommand="SELECT [SupplierID], [CompanyName] FROM [Suppliers]">
                            </asp:SqlDataSource>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("SupplierID") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="CategoryID" SortExpression="CategoryID">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("CategoryID") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("CategoryID") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" 
                        SortExpression="UnitPrice" />
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" 
                DeleteCommand="DELETE FROM [Products] WHERE [ProductID] = @ProductID" 
                InsertCommand="INSERT INTO [Products] ([ProductName], [SupplierID], [CategoryID], [UnitPrice]) VALUES (@ProductName, @SupplierID, @CategoryID, @UnitPrice)" 
                SelectCommand="SELECT [ProductID], [ProductName], [SupplierID], [CategoryID], [UnitPrice] FROM [Products]" 
                UpdateCommand="UPDATE [Products] SET [ProductName] = @ProductName, [SupplierID] = @SupplierID, [CategoryID] = @CategoryID, [UnitPrice] = @UnitPrice WHERE [ProductID] = @ProductID">
                <DeleteParameters>
                    <asp:Parameter Name="ProductID" Type="Int32" />
                </DeleteParameters>
                <UpdateParameters>
                    <asp:Parameter Name="ProductName" Type="String" />
                    <asp:Parameter Name="SupplierID" Type="Int32" />
                    <asp:Parameter Name="CategoryID" Type="Int32" />
                    <asp:Parameter Name="UnitPrice" Type="Decimal" />
                    <asp:Parameter Name="ProductID" Type="Int32" />
                </UpdateParameters>
                <InsertParameters>
                    <asp:Parameter Name="ProductName" Type="String" />
                    <asp:Parameter Name="SupplierID" Type="Int32" />
                    <asp:Parameter Name="CategoryID" Type="Int32" />
                    <asp:Parameter Name="UnitPrice" Type="Decimal" />
                </InsertParameters>
            </asp:SqlDataSource>
        </div>
        </form>
    </body>
    </html>
    

     If you decide to cut and paste this into a page you need the NORTHWIND database and of course fix the connection string  so I am going to give you my web config ( if you know how to this then ignore this)

    1    
    2    <!-- 
    3        Note: As an alternative to hand editing this file you can use the 
    4        web admin tool to configure settings for your application. Use
    5        the Website->Asp.Net Configuration option in Visual Studio.
    6        A full list of settings and comments can be found in 
    7        machine.config.comments usually located in 
    8        \Windows\Microsoft.Net\Framework\v2.x\Config 
    9    -->
    10   <configuration>
    11   
    12     <configSections>
    13       <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    14         <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    15           <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    16           <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    17             <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
    18             <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    19             <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    20             <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    21           </sectionGroup>
    22         </sectionGroup>
    23       </sectionGroup>
    24     </configSections>
    25     <appSettings>
    26       <add key="SelectedConnString" value="LocalSqlServer"/>
    27       <add key="AppName" value="ExploringTemplates"/>
    28     </appSettings>
    29     <connectionStrings>
    30       <remove name="LocalSqlServer"/>
    31       <add name="LocalSqlServer" connectionString="Data Source=.\SQLEXPRESS;database=northwind;user id=sa;password=lord;" providerName="System.Data.SqlClient"/>
    32       <add name="LocalSqlServerAW" connectionString="Data Source=.\SQLEXPRESS;database=AdventureWorks;user id=sa;password=lord;" providerName="System.Data.SqlClient"/>
    33       <add name="NorthwindConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
    34       <add name="PubsConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Pubs;Integrated Security=True" providerName="System.Data.SqlClient"/>
    35       <add name="ConnectionString" connectionString="Data Source=atcdev;User ID=atcdb;Password=lord;Unicode=True" providerName="System.Data.OracleClient"/>
    36     </connectionStrings>
    37   	<system.web>
    38   		<!-- 
    39               Set compilation debug="true" to insert debugging 
    40               symbols into the compiled page. Because this 
    41               affects performance, set this value to true only 
    42               during development.
    43   
    44               Visual Basic options:
    45               Set strict="true" to disallow all data type conversions 
    46               where data loss can occur. 
    47               Set explicit="true" to force declaration of all variables.
    48           -->
    49   		<compilation debug="true" strict="false" explicit="true">
    50   		</compilation>
    51   		<pages>
    52   			<namespaces>
    53   				<clear/>
    54   				<add namespace="System"/>
    55   				<add namespace="System.Collections"/>
    56   				<add namespace="System.Collections.Generic"/>
    57   				<add namespace="System.Collections.Specialized"/>
    58   				<add namespace="System.Configuration"/>
    59   				<add namespace="System.Text"/>
    60   				<add namespace="System.Text.RegularExpressions"/>
    61   				<add namespace="System.Web"/>
    62   				<add namespace="System.Web.Caching"/>
    63   				<add namespace="System.Web.SessionState"/>
    64   				<add namespace="System.Web.Security"/>
    65   				<add namespace="System.Web.Profile"/>
    66   				<add namespace="System.Web.UI"/>
    67   				<add namespace="System.Web.UI.WebControls"/>
    68   				<add namespace="System.Web.UI.WebControls.WebParts"/>
    69   				<add namespace="System.Web.UI.HtmlControls"/>
    70   			</namespaces>
    71   		</pages>
    72   		<!--
    73               The <authentication> section enables configuration 
    74               of the security authentication mode used by 
    75               ASP.NET to identify an incoming user. 
    76           -->
    77   		<authentication mode="Windows"/>
    78   		<!--
    79               The <customErrors> section enables configuration 
    80               of what to do if/when an unhandled error occurs 
    81               during the execution of a request. Specifically, 
    82               it enables developers to configure html error pages 
    83               to be displayed in place of a error stack trace.
    84   
    85           <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
    86               <error statusCode="403" redirect="NoAccess.htm" />
    87               <error statusCode="404" redirect="FileNotFound.htm" />
    88           </customErrors>
    89           -->
    90   	</system.web>
    91   </configuration>
    92   
    
     
    I am not anti social, am just not user friendly
  • Re: About the dropdownlist embedded into Gridview

    02-28-2008, 7:36 AM
    • Member
      358 point Member
    • hlp4al
    • Member since 06-23-2007, 5:50 AM
    • Posts 83

     Hi..

    you have to write the code in codebehind form

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

            Dim b As dropdownlist

            If e.Row.RowType = DataControlRowType.DataRow Then
                b = e.Row.Cells(0).FindControl("dropdownlist")
               
            End If

        End Sub

    and access the dropdownlist value  here

    Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
    mydatasource2.updatecommand="Update book set isbn=@isbn, book_name=@book_name, qty_in_stock=@qty_in_stock, cost=@cost, book_img=@book_img, editor_name=@editor_name, category_id=@category_id,description=@description, qty_sell=@qty_sell where categotyname=b.selectedvalue "

    mydatasource2.databind()
        End Sub

    Try above logic you can get it.. 

  • Re: About the dropdownlist embedded into Gridview

    02-28-2008, 10:20 AM
    • Contributor
      5,201 point Contributor
    • aamador
    • Member since 02-11-2008, 5:49 PM
    • Posts 1,107

    I am afraid that you do not have to write code behind just to bind a drop down list  that is a template of a gridview. You can do this all declarative ( as much as it pains me to say that) the example I posted is a running example and living proof that you don't have to write code to achieve that.  Okay having said that I prefer to write code but remember that this person told us he or she is a newbie.  So the Declarative approach is a good first step.

    I am not anti social, am just not user friendly
Page 1 of 1 (6 items)