Hi EmadKhan,
Please refer the below code and modify as per your requirement. I have referring the below article cascading sql database.
HTML
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1" DisplayAfter="30000"
DynamicLayout="True" runat="server">
<ProgressTemplate>
Loading
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" placeholder="Type 0 to delete all rows"></asp:TextBox><asp:Button
ID="Button1" OnClick="Button1_OnClick" runat="server" Text="Button" />
<asp:GridView ID="grvStudentDetails" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" OnRowDataBound="grvStudentDetails_OnRowDataBound"
GridLines="None" OnRowDeleting="grvStudentDetails_RowDeleting">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" Visible="False" />
<asp:TemplateField HeaderText="Project Category Type">
<ItemTemplate>
<asp:DropDownList ID="Categ" AutoPostBack="True" OnSelectedIndexChanged="Categ_OnSelectedIndexChanged"
runat="server">
</asp:DropDownList>
<asp:Label ID="SelVal" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project Sub-Category & Type">
<ItemTemplate>
<asp:DropDownList ID="SubCategAndType" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="quantity" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
</div>
C#
private DataTable CategoryTable;
Snippets SnippetsClass = new Snippets();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["Lang"] = "English";
}
}
protected void grvStudentDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
var dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count >= 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
grvStudentDetails.DataSource = dt;
grvStudentDetails.DataBind();
for (int i = 0; i < grvStudentDetails.Rows.Count - 1; i++)
{
grvStudentDetails.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
}
SetPreviousData();
}
if (dt.Rows.Count == 0)
{
TextBox1.Text = string.Empty;
}
}
}
private void FirstGridViewRow()
{
var dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(int)));
dt.Columns.Add(new DataColumn("Categ", typeof(string)));
dt.Columns.Add(new DataColumn("SubCategAndType", typeof(string)));
dt.Columns.Add(new DataColumn("quantity", typeof(string)));
dt.Columns.Add(new DataColumn("SelVal", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Categ"] = string.Empty;
dr["SubCategAndType"] = string.Empty;
dr["quantity"] = string.Empty;
if (grvStudentDetails.Rows.Count == 0)
{
dr["SelVal"] = "3";
}
else
{
dr["SelVal"] = string.Empty;
}
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grvStudentDetails.DataSource = dt;
grvStudentDetails.DataBind();
}
private void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
var dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
var Categ = (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("Categ");
var SubCategAndType =
(DropDownList)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("SubCategAndType");
var quantity = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("quantity");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Categ"] = Categ.SelectedValue;
dtCurrentTable.Rows[i - 1]["SubCategAndType"] = SubCategAndType.SelectedValue;
dtCurrentTable.Rows[i - 1]["quantity"] = quantity.Text;
dtCurrentTable.Rows[i - 1]["SelVal"] = Categ.SelectedValue;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
grvStudentDetails.DataSource = dtCurrentTable;
grvStudentDetails.DataBind();
SetPreviousData();
}
}
else
{
Response.Write("ViewState is null");
}
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
var dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
var Categ = (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("Categ");
var SelVal = (Label)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("SelVal");
var SubCategAndType =
(DropDownList)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("SubCategAndType");
var quantity = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("quantity");
Categ.SelectedValue = dt.Rows[i]["Categ"].ToString();
SubCategAndType.SelectedValue = dt.Rows[i]["SubCategAndType"].ToString();
quantity.Text = dt.Rows[i]["quantity"].ToString();
SelVal.Text = dt.Rows[i]["Categ"].ToString() != "" ? dt.Rows[i]["Categ"].ToString() : Categ.SelectedValue;
rowIndex++;
}
}
}
}
private void SetRowData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
var dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
var Categ = (DropDownList)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("Categ");
var SelVal = (Label)grvStudentDetails.Rows[rowIndex].Cells[1].FindControl("SelVal");
var SubCategAndType =
(DropDownList)grvStudentDetails.Rows[rowIndex].Cells[2].FindControl("SubCategAndType");
var quantity = (TextBox)grvStudentDetails.Rows[rowIndex].Cells[3].FindControl("quantity");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Categ"] = Categ.SelectedValue;
dtCurrentTable.Rows[i - 1]["SubCategAndType"] = SubCategAndType.SelectedValue;
dtCurrentTable.Rows[i - 1]["quantity"] = quantity.Text;
dtCurrentTable.Rows[i - 1]["SelVal"] = SelVal.Text;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
grvStudentDetails.DataSource = dtCurrentTable;
grvStudentDetails.DataBind();
SetPreviousData();
}
}
else
{
Response.Write("ViewState is null");
}
}
protected void Button1_OnClick(object sender, EventArgs e)
{
try
{
if (grvStudentDetails.Rows.Count == 0)
{
FirstGridViewRow();
}
if (!string.IsNullOrEmpty(TextBox1.Text) && int.Parse(TextBox1.Text) > 0)
{
grvStudentDetails.Visible = true;
if (grvStudentDetails.Rows.Count < int.Parse(TextBox1.Text))
{
int sum = int.Parse(TextBox1.Text) - grvStudentDetails.Rows.Count;
for (int i = 0; i < sum; i++)
{
AddNewRow();
}
}
}
else if (int.Parse(TextBox1.Text) == 0)
{
grvStudentDetails.Visible = false;
ViewState["CurrentTable"] = null;
ViewState["CategoryTable"] = null;
grvStudentDetails.DataSource = null;
grvStudentDetails.DataBind();
}
}
catch (Exception exception)
{
Label1.Text = exception.Message + " " + exception.StackTrace;
}
}
protected void grvStudentDetails_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
SqlCommand cmd;
if (e.Row.RowType == DataControlRowType.DataRow)
{
try
{
if (ViewState["CategoryTable"] == null)
{
string query = "SELECT [CountryId],[CountryName] FROM [Countries]";
//"SELECT [id],[description] FROM [dbo].[system_config_parameters] WHERE type = 'Project Type' ORDER BY id asc";
using (cmd = new SqlCommand(query))
{
CategoryTable = (DataTable)SnippetsClass.ExecuteQuery(cmd, "SELECT");
ViewState["CategoryTable"] = CategoryTable;
}
}
var categ = (DropDownList)e.Row.FindControl("Categ");
categ.DataSource = ViewState["CategoryTable"];
categ.DataTextField = "CountryName";
categ.DataValueField = "CountryId";
categ.DataBind();
foreach (ListItem item in categ.Items)
{
//item.Text = dataLangTable.Select("Master = '" + item.Text.Trim() + "'")[0][1].ToString().Trim();
}
var SubCategAndType = (DropDownList)e.Row.FindControl("SubCategAndType");
var SelVal = (Label)e.Row.FindControl("SelVal");
SelVal.Text = categ.SelectedItem.Value;
cmd = new SqlCommand("SELECT [StateId] ,[CountryId],[StateName] FROM [States]");
//var com = new SqlCommand("sp_BindSubCateg_Type_PMP");
//com.CommandType = CommandType.StoredProcedure;
//com.Parameters.AddWithValue("@language", Session["Lang"].ToString());
//com.Parameters.AddWithValue("@mainCategID", int.Parse(SelVal.Text));
var dt = (DataTable)SnippetsClass.ExecuteQuery(cmd, "SELECT");
SubCategAndType.DataTextField = "StateName";
SubCategAndType.DataValueField = "StateId";
SubCategAndType.DataSource = dt;
SubCategAndType.DataBind();
}
catch (Exception exception)
{
Label1.Text = exception.Message + " " + exception.StackTrace;
}
}
}
protected void Categ_OnSelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd;
try
{
var Categ = (DropDownList)sender;
var currentRow = (GridViewRow)Categ.NamingContainer;
var SubCategAndType = (DropDownList)currentRow.FindControl("SubCategAndType");
var categ = (DropDownList)currentRow.FindControl("categ");
var SelVal = (Label)currentRow.FindControl("SelVal");
SelVal.Text = categ.SelectedValue.Trim();
//var com = new SqlCommand("sp_BindSubCateg_Type_PMP");
//com.CommandType = CommandType.StoredProcedure;
//com.Parameters.AddWithValue("@language", Session["Lang"].ToString());
//com.Parameters.AddWithValue("@mainCategID", Categ.SelectedItem.Value);
//var dt = (DataTable)SnippetsClass.ExecuteQuery(com, "SP");
//SubCategAndType.DataTextField = "Description";
//SubCategAndType.DataValueField = "ID";
cmd = new SqlCommand("SELECT [StateId] ,[CountryId],[StateName] FROM [States] WHERE CountryId=" + categ.SelectedValue);
//var com = new SqlCommand("sp_BindSubCateg_Type_PMP");
//com.CommandType = CommandType.StoredProcedure;
//com.Parameters.AddWithValue("@language", Session["Lang"].ToString());
//com.Parameters.AddWithValue("@mainCategID", int.Parse(SelVal.Text));
var dt = (DataTable)SnippetsClass.ExecuteQuery(cmd, "SELECT");
SubCategAndType.DataTextField = "StateName";
SubCategAndType.DataValueField = "StateId";
SubCategAndType.DataSource = dt;
SubCategAndType.DataBind();
}
catch (Exception exception)
{
Label1.Text = exception.Message + " " + exception.StackTrace;
}
}
Snippets class
public class Snippets
{
public DataTable ExecuteQuery(SqlCommand cmd, string action)
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ToString();
SqlConnection con = new SqlConnection(constring);
cmd.Connection = con;
if (action == "SELECT")
{
cmd.CommandType = CommandType.Text;
}
if (action == "SP")
{
cmd.CommandType = CommandType.StoredProcedure;
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
Screenshot