Click here to Skip to main content
14,603,943 members
Rate this:
Please Sign up or sign in to vote.
See more:
Please, help me to solve this:
I have a DropDownList, its items are country names. I would like to add the selected item of the DropDownList to a GridView after clicking a CommandButton. The GridView is composed of two columns: a BoundField Country and a DropDownList TemplateField City to show cities belongs to the selected country.
My Issue is; when inserting a new row, the DropDownList TemplateField in all rows is updated to values of the DropDownList in last inserted row.

What I want is when selecting India and submit City list should contain (Delhi, Ahmad Abad, ...)
What I want is when selecting UAE and submit City list should contain (Abu Dhabi,Dubai, ...)
and first row should not be affected.

What I have tried:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DropDownListInGridView.WebForm1" %>

<!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:Label runat="server">Country</asp:Label>
        <asp:DropDownList runat="server" ID="ddlCounty" Width = "200px" 

            AutoPostBack="True">
        </asp:DropDownList>
         
        <asp:Button ID="btnAppend" runat="server" Text="Append" Width = "100px" 

            onclick="btnAppend_Click" />
    </div>

    <br />
    <div>
        <asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="False" 

            Width = "300px" onrowdatabound="gvDetails_RowDataBound" >
            <Columns>
                <asp:BoundField DataField="CountryName" HeaderText="Country" />
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlCity" runat="server" Width = "98%">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


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

namespace DropDownListInGridView
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        static string Con = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        SqlConnection sqlCon = new SqlConnection(Con);
        SqlCommand cmd;
        SqlDataAdapter da;
        DataTable dt;
        static DataTable dtGrid = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                cmd = new SqlCommand();
                cmd.Connection = sqlCon;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM tlkCountry";
                try
                {
                    dt = new DataTable();
                    sqlCon.Open();
                    da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    sqlCon.Close();
                    ddlCounty.DataSource = dt;
                    ddlCounty.DataTextField = "CountryName";
                    ddlCounty.DataValueField = "CountryID";
                    ddlCounty.DataBind();

                    dtGrid.Columns.Add("CountryName");
                }
                catch (Exception ex)
                {
                    
                }
            }
            
        }

        protected void btnAppend_Click(object sender, EventArgs e)
        {
            int i;
            dtGrid.Rows.Add();
            i = dtGrid.Rows.Count - 1;
            dtGrid.Rows[i]["CountryName"] = ddlCounty.SelectedItem.Text;

            gvDetails.DataSource = dtGrid;
            gvDetails.DataBind();            
        }

        protected void GetCitiesList(DropDownList ddl)
        {
            cmd = new SqlCommand();
            cmd.Connection = sqlCon;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT CityID, CityName FROM tlkCity WHERE CountryID = " +ddlCounty.SelectedValue;
            try
            {
                dt = new DataTable();
                sqlCon.Open();
                da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                sqlCon.Close();
                string s = dt.Rows.Count.ToString();
                ddl.DataSource = dt;
                ddl.DataTextField = "CityName";
                ddl.DataValueField = "CityID";
                ddl.DataBind();
            }
            catch (Exception ex)
            {
            }
        }

        protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DropDownList[] _ddl= new DropDownList[10];
                _ddl[e.Row.RowIndex]= e.Row.FindControl("ddlCity") as DropDownList;
                GetCitiesList(_ddl[e.Row.RowIndex]);
            }
        }
    }
}


CREATE TABLE [dbo].[tlkCountry](
	[CountryID] [int] IDENTITY(1,1) NOT NULL,
	[CountryName] [nvarchar](50) NULL
)

CREATE TABLE [dbo].[tlkCity](
	[CityID] [int] IDENTITY(1,1) NOT NULL,
	[CountryID] [int] NULL,
	[CityName] [nvarchar](50) NULL
) 
Posted
Updated 23-Nov-19 23:50pm
v3
Comments
Richard Deeming 27-Nov-19 14:45pm
   
cmd.CommandText = "SELECT CityID, CityName FROM tlkCity WHERE CountryID = " +ddlCounty.SelectedValue;

Don't do it like that!

Whilst in this particular instance you're probably safe, using string concatenation to build SQL queries can and will lead to SQL Injection[^] vulnerabilities.

ALWAYS use a parameterized query.
cmd.CommandText = "SELECT CityID, CityName FROM tlkCity WHERE CountryID = @CountryID";
cmd.Parameters.AddWithValue("@CountryID", ddlCounty.SelectedValue);
Mohd.Mekki 28-Nov-19 1:43am
   
thanks a lot. Advice appreciated.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 2

   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100