Click here to Skip to main content
15,888,257 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a simple gridview pulling data from a SQL-server database table. It has 2 cascading dropdown lists. It’s a simple practice asp.net web application in C#. I am using a “commandfield” for the “edit” column.
What I am trying to do is set the dropdown lists in gridview to retain their current values when I click the edit button. As it is, when I click the edit button it refreshes the page / gridview and sets the second dropdown list back to the first selection in the menu. I want it to keep its original value unless the first dropdown list is changed.
This will allow me to change other boxes without affecting the two dropdown lists.
This simple gridview only has 5 columns:
Modify – (for the edit button)
ID – (a non-editable column)
Name – (a simple text box)
Manufacturer – ( 1st DropDown List “ddlManufacturer”)
Model – ( 2nd DropDown List “ddlModel”)

I have tried setting “AutoPostBack=false” on the gridview and on both dropdown lists.
I have also tried changing the “e.NewValue” commands on the aspx.cs page to “e.OldValue” but nothing seems to work. Every time I click edit it resets the second dropdown list to the first value in the list.
Any help would be greatly appreciated.
Thanks.

What I have tried:

My aspx code:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <div>


<%-- GRIDVIEW --%>

<div>
    <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" OnRowUpdating="GridView1_RowUpdating"
AutoGenerateColumns="False" DataKeyNames="CustomerId" CellPadding="4" ForeColor="#333333" GridLines="Both" >
        <AlternatingRowStyle BackColor="White" />

<Columns>
<%-- Modify Column --%>
<asp:CommandField ShowEditButton="True" HeaderText="Modify" />

<%-- CustomerId Column --%>
    <asp:BoundField DataField="CustomerId" HeaderText="ID" SortExpression="CustomerId" ReadOnly="true" /> 

<%-- Name Column --%>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

<%-- Manufacturer Column --%>
<asp:TemplateField HeaderText="Manufacturer" SortExpression="Manufacturer">
<EditItemTemplate>
<asp:DropDownList ID="ddlManufacturer" runat="server" AutoPostBack="True" DataTextField="Manufacturer"
DataValueField="Manufacturer" Width="122px" SelectedValue='<%# Bind("Manufacturer") %>'
DataSourceID="SqlDataSource2" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CarsConnectionString %>"
SelectCommand="SELECT [Manufacturer] FROM Manufacturer"></asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Manufacturer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<%-- Model Column --%>
<asp:TemplateField HeaderText="Model" SortExpression="Model">
<EditItemTemplate>
Model:
<asp:DropDownList ID="ddlModel" runat="server" DataSourceID="SqlDataSource3" DataTextField="Model" DataValueField="Model">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="ddlModel" InitialValue="Select" ErrorMessage="Select a Model" ></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:CarsConnectionString %>"
SelectCommand="SELECT [Model],[Manufacturer] FROM [Model] "  FilterExpression="[Manufacturer]= '{0}'">
<FilterParameters><asp:ControlParameter ControlID="ddlManufacturer" Name="Manufacturer" PropertyName="SelectedValue" Type="String" />
</FilterParameters>
</asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Model") %>'></asp:Label>
   
</ItemTemplate>
   
</asp:TemplateField>

</Columns>

<%-- GridView Color Scheme --%>
        <EditRowStyle BackColor="#7C6F57" />
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#E3EAEB" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#F8FAFA" />
        <SortedAscendingHeaderStyle BackColor="#246B61" />
        <SortedDescendingCellStyle BackColor="#D4DFE1" />
        <SortedDescendingHeaderStyle BackColor="#15524A" />

</asp:GridView>

<%-- DataSource for GridView --%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CarsConnectionString %>"
    
SelectCommand="SELECT [CustomerId], [Name], [Manufacturer], [Model] FROM [Customers] ORDER BY CustomerId"
InsertCommand="INSERT INTO [Customers] ([Name], [Manufacturer], [Model]) VALUES (@Name, @Manufacturer, @Model)"
UpdateCommand="UPDATE [Customers] SET [Name] = @Name, [Manufacturer] = @Manufacturer, [Model] = @Model WHERE [CustomerId] = @CustomerId"
DeleteCommand="DELETE FROM [Customers] WHERE [CustomerId] = @CustomerId">

</asp:SqlDataSource>

</div>
</div>
    
</asp:Content>


My aspx.cs (code behind):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Sql;
using System.Data;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace CascadingGridview6
{
    public partial class Contact : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
            }
        }

        SqlConnection con = new SqlConnection(@"Data Source=dsouthres18v;Initial Catalog=Cars;Integrated Security=True");

        public int NewEditIndex { get; private set; }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            
            string strModel = ((DropDownList)((GridView)sender).Rows[e.RowIndex].FindControl("ddlModel")).SelectedValue;
            string strManufacturer = ((DropDownList)((GridView)sender).Rows[e.RowIndex].FindControl("ddlManufacturer")).SelectedValue;
            e.NewValues[
            "Model"] = strModel;
            e.NewValues[
            "Manufacturer"] = strManufacturer;
            e.Cancel =
            false;
            GridView gv = (GridView)sender;
            for (int i = 0; i < gv.Columns.Count; i++)
            {
                DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
                gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell,
                DataControlRowState.Edit, true);
            }
        }

        
    }
}
Posted
Updated 4-Feb-19 10:08am
Comments
Karthik_Mahalingam 31-Aug-17 3:52am    
did you try with update panel ?
[no name] 31-Aug-17 11:32am    
I was thinking about that but if I put the gridview in an update panel; when I click the edit button (that is in the gridview) that will update / refresh the gridview even if it's in an update panel. (I think) I am not real familiar with how update panel works. Thanks for the suggestion.
[no name] 6-Sep-17 10:01am    
I'm still looking for an answer on this question if anyone can assist me. Is this even possible? Thanks.
[no name] 6-Sep-17 10:30am    
On a side note, update panel does not work. I tried nesting both drop-down list in an update panel and I tried nesting each part of the 2 drop-down menus. Nothing is working yet. Please advise. Thank you.

1 solution

UPDATE
I have figured out a solution to my problem, which I am sure there are others who would like to know the answer. So, here it is,
My code was basically on track, I was only missing a couple of items.

First; I copied the "asp:Label…. " command from the "ItemTemplate" section of the "Model" column and pasted it in the "EditItemTemplate" just above the dropdown list and added the value (Visible="false") to the end of the statement.


Second; I added the following (GridView1_RowDataBound) method to the "aspx.cs" page just above the existing (GridView1_RowUpdating) method and populated it with the following code –


if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {

                    DropDownList DDL2 = e.Row.FindControl("ddlModel") as DropDownList;       // 2nd ddl (Region)

                    Label LBL2 = e.Row.FindControl("Label1") as Label;       // label in "edit" mode on second ddl

                    DDL2.DataBind();
                    DDL2.SelectedValue = Convert.ToString(LBL2.Text);
                }
            }


Finally, I added the (OnRowDataBound=”GridView1_RowDataBound”) command to the head of the Gridview where you actually call the Gridview.

Here is the full source code for both pages:
HTML page (default.aspx)

<%@ Page Title="Cascading Gridview" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="WebApplication1.About" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Customerid" DataSourceID="SqlDataSource1" 
        CellPadding="4" ForeColor="#333333" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound">
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <%-- Edit Column --%>
            <asp:CommandField ShowEditButton="true" />

            <%-- CustomerId Column --%>
            <asp:BoundField DataField="Customerid" HeaderText="Customerid" InsertVisible="False" ReadOnly="True" SortExpression="Customerid" />

            <%-- Name Column --%>
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />

            <%-- Manufacturer Column --%>
            <asp:TemplateField HeaderText="Manufacturer" SortExpression="Manufacturer">
                <EditItemTemplate>
                    
                    <%--<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Manufacturer") %>'></asp:TextBox>--%>

                    <%-- Dropdown List --%>
                    <asp:DropDownList ID="ddlManufacturer" runat="server" AutoPostBack="true" DataTextField="Manufacturer"
                        DataValueField="Manufacturer" SelectedValue='<%# Bind("Manufacturer") %>' DataSourceID="SqlDataSource2" >
                    </asp:DropDownList>

                    <%-- SQL DataSource --%>
                    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:conString %>"
                        SelectCommand="SELECT [Manufacturer] FROM Manufacturer"></asp:SqlDataSource>
                </EditItemTemplate>

                    <%-- Label --%>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Manufacturer") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <%-- Model Column --%>
            <asp:TemplateField HeaderText="Model" SortExpression="Model">
                <EditItemTemplate>
                    <%--<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Model") %>'></asp:TextBox>--%>

                     <%-- Label --%>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Model") %>' Visible="false"></asp:Label>

                     <%-- DropDownList --%>
                    <asp:DropDownList ID="ddlModel" runat="server" DataSourceID="SqlDataSource3" DataTextField="Model" DataValueField="Model" >
                    </asp:DropDownList>

                    <%-- Data Source --%>
                    <asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:conString %>"
                    SelectCommand="SELECT [Model],[Manufacturer] FROM [Model] " FilterExpression="[Manufacturer]= '{0}'">
                    <FilterParameters><asp:ControlParameter ControlID="ddlManufacturer" Name="Manufacturer" PropertyName="SelectedValue" Type="String" />
                    </FilterParameters>
                    </asp:SqlDataSource>
                </EditItemTemplate>

                <%-- Label --%>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("Model") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

            <%-- ID Column --%>
            <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />

        </Columns>
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        <SortedAscendingCellStyle BackColor="#FDF5AC" />
        <SortedAscendingHeaderStyle BackColor="#4D0000" />
        <SortedDescendingCellStyle BackColor="#FCF6C0" />
        <SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:conString %>" 
    SelectCommand="SELECT [CustomerId], [Name], [Manufacturer], [Model], [id] FROM [Customers] ORDER BY CustomerId"
    UpdateCommand="UPDATE [Customers] SET [Name]=@Name, [Manufacturer]=@Manufacturer, [Model]=@Model WHERE [CustomerId]=@CustomerId"></asp:SqlDataSource>
</asp:Content>


Code behind page (default.aspx.cs)

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class About : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {

                    DropDownList DDL2 = e.Row.FindControl("ddlModel") as DropDownList;       // 2nd ddl (Region)

                    Label LBL2 = e.Row.FindControl("Label1") as Label;       // label in "edit" mode on second ddl

                    DDL2.DataBind();
                    DDL2.SelectedValue = Convert.ToString(LBL2.Text);
                }
            }
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string strModel = ((DropDownList)((GridView)sender).Rows[e.RowIndex].FindControl("ddlModel")).SelectedValue;
            string strManufacturer = ((DropDownList)((GridView)sender).Rows[e.RowIndex].FindControl("ddlManufacturer")).SelectedItem.Value;
            e.NewValues[
            "Model"] = strModel;
            e.NewValues[
            "Manufacturer"] = strManufacturer;
            e.Cancel =
            false;
            GridView gv = (GridView)sender;
            for (int i = 0; i < gv.Columns.Count; i++)
            {
                DataControlFieldCell cell = gv.Rows[e.RowIndex].Cells[i] as DataControlFieldCell;
                gv.Columns[i].ExtractValuesFromCell(e.NewValues, cell,
                DataControlRowState.Edit, true);
            }
        }
    }
}
 
Share this answer
 
v2
Comments
Maciej Los 4-Feb-19 16:18pm    
+5 for your effort.
[no name] 4-Feb-19 16:52pm    
Thanks for the 5 star.
Please feel free to share the answer with anyone having the same issue.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900