Hi bakhtawar,
I have created sample. Please refer the below code.
HTML
<div align="center">
<table>
<tr>
<td>
<asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="true" OnSelectedIndexChanged="DropdownChanged"
AppendDataBoundItems="true">
<asp:ListItem Text="-Select-" Value="-Select-" />
</asp:DropDownList>
</td>
<td>
<asp:GridView runat="server" ID="gvDetails" />
</td>
</tr>
</table>
</div>
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("No"), new DataColumn("Name") });
dt.Rows.Add("rs23", "John Hammond");
dt.Rows.Add("rs24", "Mudassar Khan");
dt.Rows.Add("rs25", "Suzanne Mathews");
dt.Rows.Add("rs26", "Robert Schidner");
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "No";
DropDownList1.DataValueField = "No";
DropDownList1.DataBind();
}
}
protected void DropdownChanged(object sender, EventArgs e)
{
string selectedValue = DropDownList1.SelectedValue;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("No"), new DataColumn("Name") });
if (Session["Data"] != null)
{
dt = Session["Data"] as DataTable;
if (selectedValue != "-Select-")
{
DataRow[] existRow = dt.Select("No='" + selectedValue + "'");
if (existRow.Length > 0)
{
if (existRow[0].ItemArray[0].ToString().ToLower() != selectedValue.ToLower())
{
dt.Rows.Add(selectedValue, selectedValue);
Session["Data"] = dt;
}
else
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Value " + selectedValue + " already exist.')", true);
}
}
else
{
dt.Rows.Add(selectedValue, selectedValue);
Session["Data"] = dt;
}
}
}
else
{
dt.Rows.Add(selectedValue, selectedValue);
Session["Data"] = dt;
}
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
Screenshot
