I am creating a dynamically repeater during the creation of this repeater I create some dropdownlists with autopostback = true, and add the handler selectindexchanged. I wonder how to keep bind the repeater inside (! IsNotPostBack) without losing the repeater information. In summary if I keep bind the repeater in notpostback, when I change the dropdownlist the repeater is not rendered.
Well confused? I will post part of the code:
Default.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater2();
}
}
private void BindRepeater2()
{
Repeater rContainer = null;
HtmlGenericControl div = new HtmlGenericControl("div");
HtmlGenericControl table = new HtmlGenericControl("table");
div.Attributes.Add("class", "CompApp_TableScroll");
table.Attributes.Add("class", "CompApp_DataTable");
table.Attributes.Add("width", "100%");
try
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Address", typeof(string));
dt.Columns.Add("DropDown", typeof(string));
dt.Rows.Add(25, "Rk", "Gurgaon");
dt.Rows.Add(50, "Sachin", "Noida");
dt.Rows.Add(10, "Nitin", "Noida");
dt.Rows.Add(21, "Aditya", "Meerut");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
if (dt.Rows.Count > 0)
{
rContainer = new Repeater();
rContainer.DataSource = dt;
rContainer.DataBind();
foreach (DataTable dtCluster in ds.Tables)
{
rContainer = new Repeater();
rContainer.ItemTemplate = new RepeaterTemplate2(ListItemType.Item);
rContainer.HeaderTemplate = new RepeaterTemplate2(ListItemType.Header);
rContainer.FooterTemplate = new RepeaterTemplate2(ListItemType.Footer);
rContainer.DataSource = dtCluster;
table.Controls.Add(rContainer);
}
div.Controls.Add(table);
}
div1.Controls.Add(div);
rContainer.ItemDataBound += rContainer_ItemDataBound;
rContainer.ID = "rpt1";
rContainer.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
void rContainer_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = new DropDownList();
ddl = (DropDownList)e.Item.FindControl("ddl");
ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
}
}
private void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl2 = new DropDownList();
ddl2 = (DropDownList)sender;
Response.Write(ddl2.SelectedValue);
}
RepeaterTemplate2.cs
public class RepeaterTemplate2 : System.Web.UI.ITemplate
{
ListItemType vTemplateItemType = ListItemType.Separator;
public RepeaterTemplate2(ListItemType pListItemType)
{
vTemplateItemType = pListItemType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
Literal lc = new Literal();
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
switch (vTemplateItemType)
{
case ListItemType.Header:
td.InnerHtml = "<u>EmpID</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>Name</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>Address</u>";
tr.Controls.Add(td);
td = new HtmlGenericControl("td");
td.InnerHtml = "<u>DropdDown</u>";
tr.Controls.Add(td);
break;
case ListItemType.Footer:
break;
case ListItemType.Item:
; break;
}
tr.DataBinding += new EventHandler(lc_DataBinding);
container.Controls.Add(tr);
}
private void lc_DataBinding(object sender, EventArgs e)
{
HtmlGenericControl tr = (HtmlGenericControl)sender;
RepeaterItem vContainer = (RepeaterItem)tr.NamingContainer;
DataRowView row = (DataRowView)vContainer.DataItem;
if (row != null)
{
for (int i = 0; i < row.DataView.Table.Columns.Count; i++)
{
HtmlGenericControl td = new HtmlGenericControl("td");
if (i == 3)
{
DropDownList ddl = new DropDownList();
ddl.ID = "ddl";
ddl.Items.Add(new ListItem("valor 1", "1"));
ddl.Items.Add(new ListItem("valor 2", "2"));
td.Controls.Add(ddl);
}
else
{
td.InnerHtml = row[i].ToString();
}
tr.Controls.Add(td);
}
}
}
}
Related
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.Count > 0)
{
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from personalization where ponumber = '" + Request.QueryString["PO"] + "'", VisualConnect);
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
for (Int32 i = 0; i < dt.Rows.Count; i++)
{
HtmlGenericControl tr = new HtmlGenericControl("tr");
HtmlGenericControl td = new HtmlGenericControl("td");
HtmlGenericControl td1 = new HtmlGenericControl("td");
Label lbcustomename = new Label();
lbcustomename.ID = "lbline1";
lbcustomename.Text = "Recipient Name: ";
td.Controls.Add(lbcustomename);
tr.Controls.Add(td);
TextBox txtcustombox = new TextBox();
txtcustombox.ID = "txtline1";
txtcustombox.Text = dt.Rows[i]["line1"].ToString();
td1.Controls.Add(txtcustombox);
tr.Controls.Add(td1);
placeholder.Controls.Add(tr);
//Add button after last record
if (i == dt.Rows.Count - 1)
{
tr = new HtmlGenericControl("tr");
td = new HtmlGenericControl("td");
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Click += btnSubmit_Click;
btnSubmit.Text = "Submit";
btnSubmit.Attributes.Add("runat", "server");
td.Controls.Add(btnSubmit);
td.Attributes.Add("Colspan", "2");
td.Attributes.Add("style", "text-align:center;");
tr.Controls.Add(td);
placeholder.Controls.Add(tr);
}
}
}
}
}
private void btnSubmit_Click(object sender, EventArgs e)
{
// do something
}
}
I have added this code to dynamically draw up fields from a database for input where the user would click the Submit button when completed. However, whenever I click the submit button, it wants to reload the page and the btnSubmit_Click event is never invoked instead. Am I missing something?
Currently, there is 2 values in my DropDownList which is viewProduct and editProduct. So when the user selects one of the value, it will direct user to the particular function in ASP.NET. I have tried OnSelectedIndexChanged, but it seems like not working on the dynamic DropDownList.
Here is my code:
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
if(ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if(ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
Any idea how to solve it without using JavaScript?
My entire code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private void BindGridView()
{
MySqlConnection conn = new MySqlConnection(sqlConn);
string sql = "SELECT prodID, prodName, stockLevel, reorderLevel, unitPrice from Product";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
productList.DataSource = dt;
productList.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell tc = new TableCell();
DropDownList ddlAction = new DropDownList();
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Prod ID";
e.Row.Cells[1].Text = "Product Name";
e.Row.Cells[2].Text = "Qty";
e.Row.Cells[3].Text = "Reorder Level";
e.Row.Cells[4].Text = "Price (RM)";
e.Row.Controls.Add(tc);
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
var qty = Int16.Parse(e.Row.Cells[2].Text);
var reorder = Int16.Parse(e.Row.Cells[3].Text);
if (qty <= reorder)
{
e.Row.Cells[2].CssClass = "redCell";
e.Row.Cells[3].CssClass = "redCell";
}
e.Row.Controls.Add(tc);
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
if (ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if (ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
}
}
You need to declare an event handler then assign it to the control before adding the control to the page.
Here is an example :
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
CreateControl();
}
}
protected void CreateControl()
{
var ddlAction = new DropDownList();
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
e.Row.Cells[5].Controls.Add(ddlAction);
}
protected void DDLAction_OnSelectedIndexChanged(object sender, EventArgs e)
{
var action = (DropDownList) sender;
var choice = action.SelectedValue?.Trim();
string script = null;
switch (choice)
{
case "viewProduct":
script = "alert('View page!');";
break;
case "editProduct":
script = "alert('Edit page!');";
break;
default:
script = "alert('Unmatched Value!')";
break;
}
ScriptManager.RegisterStartupScript(this , typeof(_Default) , "TestJS" , $"<script>{script}</script>" , false);
}
use ScriptManager.RegisterStartupScript when you want to work with JS scripts. Response.Write will not parse script blocks as an executable blocks. It will throw a parse error though (you could check the browser console.
I've created some dynamic checkboxes in table header row.
If the checkbox is checked , table will have another row with a textbox.
Checkbox changed event is firing very well but when I'm trying to check whether the checkbox is checked or not , it's generating exception :
Object Reference not set to an instance of an object.
Here is my code :
Creating Dynamic controls here :
TableRow thead = new TableRow();
for (int i = 0; i < dt_fundtype.Rows.Count; i++)
{
TableCell td = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "fund_" + dt_fundtype.Rows[i]["fund_type_cd"];
chk.Text = dt_fundtype.Rows[i]["fund_type"].ToString();
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(Chk_Fund_CheckedChange);
td.Controls.Add(chk);
thead.Cells.Add(td);
}
tbl_fundtype.Rows.Add(thead);
Checkbox checked changed event :
public void Chk_Fund_CheckedChange(object sender, EventArgs e)
{
TableRow tr = new TableRow();
for (int i=0;i<tbl_fundtype.Rows[0].Cells.Count;i++)
{
string DynamicChkID ="fund_"+ dt_fundtype.Rows[i]["fund_type_cd"].ToString();
CheckBox chk = new CheckBox();
chk = (CheckBox)tbl_fundtype.Rows[0].Cells[i].FindControl("DynamicChkID");
if (chk.Checked == true)//Here is the Exception
{
TableCell td = new TableCell();
td.Text = "Test";
tr.Cells.Add(td);
}
}
tbl_fundtype.Rows.Add(tr);
hfTab.Value = "fund";
collapsestate = "expand";
}
The event is firing very well , but when I check that the checkbox is checked or not there's an exception.
How can I resolve this problem ? Kindly Help me Please
This is the example I use which work for me.
I've simplified the binding logic and lookup logic etc, to illustrate
protected void Page_Load(object sender, EventArgs e)
{
AddStuff();
}
private void AddStuff()
{
TableRow thead = new TableRow();
for (int i = 0; i < 10; i++)
{
TableCell td = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "fund_" + i;
chk.Text = i.ToString();
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(Chk_Fund_CheckedChange);
td.Controls.Add(chk);
thead.Cells.Add(td);
}
tbl_fundtype.Rows.Add(thead);
}
public void Chk_Fund_CheckedChange(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
var chk = tbl_fundtype.FindControl("fund_" + i) as CheckBox;
if (chk.Checked)
{
//I am checked
}
}
}
And on my markup page I have:
<asp:Table ID="tbl_fundtype" runat="server" />
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = Rowcreation();
TableRow thead = new TableRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
TableCell td = new TableCell();
CheckBox chk = new CheckBox();
chk.ID = "fund" + dt.Rows[i]["ID"];
chk.Text = dt.Rows[i]["Name"].ToString();
chk.AutoPostBack = true;
chk.CheckedChanged += new EventHandler(chk_fun_checkedchange);
td.Controls.Add(chk);
thead.Controls.Add(td);
}
pnl.Controls.Add(thead);
}
public void chk_fun_checkedchange(object sender, EventArgs e)
{
DataTable dt = Rowcreation();
for (int i = 0; i < dt.Rows.Count; i++)
{
CheckBox chkbx = (CheckBox ) pnl.Parent.Controls[0].FindControl("fund"+dt.Rows [i]["ID"]);
if (chkbx.Checked == true)
{
lbl.Text = chkbx.Text;
}
}
}
private DataTable Rowcreation()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["ID"] = "1";
dr["Name"] = "Name1";
dt.NewRow();
dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow();
dr1["ID"] = "2";
dr1["Name"] = "Name2";
dt.Rows.Add(dr1);
dt.NewRow();
DataRow dr2 = dt.NewRow();
dr2["ID"] = "3";
dr2["Name"] = "Name3";
dt.Rows.Add(dr2);
return dt;
}
I have a gridview that has dynamically created columns.
Right now all the data is showing in its respective place but I am unable to get my link button to work. (Gridview disappears)
Here is my backend code, the gridview used is just an empty gridview
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
TemplateField tfield = new TemplateField();
tfield.HeaderText = "View";
GridView1.Columns.Add(tfield);
}
GridView1.DataBind();
}
string selectedID = null;
private void BindGrid(List<string> SelectedInfo)
{
DataTable dt = new DataTable();
//Dynamically adding columns and setting first column added as ID
selectedID = SelectedInfo[0];
for (int i = 0; i < SelectedInfo.Count; i++)
{
dt.Columns.Add(new DataColumn(SelectedInfo[i], typeof(string)));
}
List<string[]> InfoList = getInfoList(SelectedInfo);
for (int i = 0; i < InfoList.Count; i++)
{
dt.Rows.Add(InfoList[i]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ //Adding link button to first column
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[selectedID].ToString();
e.Row.Cells[0].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
//Popup the selected row ID
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Row ID" + id + "')", true);
}
protected void CheckBoxList2_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> SelectedInfo = new List<string>();
for (int i = 0; i < CheckBoxList2.Items.Count; i++)
{
if (CheckBoxList2.Items[i].Selected)
{
SelectedInfo.Add(CheckBoxList2.Items[i].Text);
}
}
BindGrid(SelectedInfo);
}
If you need to create controls at runtime, you better use the RowCreated event:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{ //Adding link button to first column
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row[selectedID].ToString();
e.Row.Cells[0].Controls.Add(lnkView);
}
}
Otherwise you have to bind your GridView on every postback inViewDetails the Page_Load event.
Anyway if your GridView disappears, it's just because you have to bind it again in the ViewDetails method.
I hope below code will help you.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
TemplateField tfield = new TemplateField();
tfield.HeaderText = "View";
GridView1.Columns.Add(tfield);
}
this.BindGrid();
}
private void BindGrid()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
dt.Rows.Add(1, "A");
dt.Rows.Add(2, "B");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[2].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + "')", true);
}
I have multiple dropdownlist box all querying the same column, same table and from the same database. For example under memberID column i have the following IDs.
12345
23456
34567
And i have 3 different dropdownlist box as shown below
<asp:DropDownList ID="memberID3" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="memberID1" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
I added update panel between the dropdownlist so as to allow my dropdownlist to refresh upon any updates/selections.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
For instance, when memberID1 selected 12345, the other 2 dropdownlist (memberID2 and 3) will not display the ID 12345. Vice versa, when memberID1 select the default value of the dropdownlist, the ID reappears in the other 2 dropdownlistbox. I have added a default value for all of the DDL.
memeberID(number).Items.Insert(0, new ListItem(" Please select a Member ID", ""));
memeberID(number).SelectedIndex = 0;
If i have not mistaken the property of update panel, isn't that able to make this function work?
here is the binding code as requested.
protected void ddllocation_SelectedIndexChanged(object sender, EventArgs e)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
memberID1.Items.Clear();
memberID1.DataSource = ds2;
memberID1.DataTextField = "memberID";
memberID1.DataValueField = "memberID";
memberID1.DataBind();
memberID1.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID1.SelectedIndex = 0;
memberID2.Items.Clear();
memberID2.DataSource = ds2;
memberID2.DataTextField = "memberID";
memberID2.DataValueField = "memberID";
memberID2.DataBind();
memberID2.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID2.SelectedIndex = 0;
memberID3.Items.Clear();
memberID3.DataSource = ds2;
memberID3.DataTextField = "memberID";
memberID3.DataValueField = "memberID";
memberID3.DataBind();
memberID3.Items.Insert(0, new ListItem("Please select a Member ID", ""));
memberID3.SelectedIndex = 0;
}
UPDATE
For now i'm able to allow my other ddl to re-bind and cache the selected value in the other dropdownlist when the default value is selected. However, when i select other ID, the ID are being removed and it wont re-bind the other ddl.
protected void FillddlLocations()
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.Visible = false;
ddlpid2.Visible = false;
ddlpid3.Visible = false;
ddlpid4.Visible = false;
ddlpid5.Visible = false;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Police ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid1.SelectedIndex > 0)
{
Session["pid1"] = ddlpid1.SelectedValue;
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid1.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else
if (ddlpid1.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid2.SelectedIndex > 0)
{
Session["pid2"] = ddlpid2.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid2.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid2.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid3.SelectedIndex > 0)
{
Session["pid3"] = ddlpid3.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid3.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid3.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid4_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid4.SelectedIndex > 0)
{
Session["pid4"] = ddlpid4.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem5 = ddlpid5.Items.FindByValue(ddlpid4.SelectedValue);
ddlpid5.Items.Remove(removeItem5);
}
else if (ddlpid4.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid5.SelectedValue = (String)Session["pid5"];
ddlpid5_SelectedIndexChanged(this, EventArgs.Empty);
}
}
protected void ddlpid5_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlpid5.SelectedIndex > 0)
{
Session["pid5"] = ddlpid5.SelectedValue;
ListItem removeItem1 = ddlpid1.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid1.Items.Remove(removeItem1);
ListItem removeItem2 = ddlpid2.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid2.Items.Remove(removeItem2);
ListItem removeItem3 = ddlpid3.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid3.Items.Remove(removeItem3);
ListItem removeItem4 = ddlpid4.Items.FindByValue(ddlpid5.SelectedValue);
ddlpid4.Items.Remove(removeItem4);
}
else if (ddlpid5.SelectedItem.Text.Equals("Police ID"))
{
FillDropdown(ddlpid1);
FillDropdown(ddlpid2);
FillDropdown(ddlpid3);
FillDropdown(ddlpid4);
FillDropdown(ddlpid5);
ddlpid1.SelectedValue = (String)Session["pid1"];
ddlpid1_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid2.SelectedValue = (String)Session["pid2"];
ddlpid2_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid3.SelectedValue = (String)Session["pid3"];
ddlpid3_SelectedIndexChanged(this, EventArgs.Empty);
ddlpid4.SelectedValue = (String)Session["pid4"];
ddlpid4_SelectedIndexChanged(this, EventArgs.Empty);
}
}
First of all, I would set the AutoPostBack property for dropdowns to true in my markup:
<asp:DropDownList ID="memberID1" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid1_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID2" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid2_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="memberID3" AutoPostBack="true" runat="server" Visible="false" OnSelectedIndexChanged="ddlpid3_SelectedIndexChanged" >
</asp:DropDownList>
Update: We can store selected values in view state and retrieve after repopulating the dropdownlists like below:
public partial class WebForm2 : System.Web.UI.Page
{
bool bFlag = true;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillddlLocations();
}
}
//Properties to store selected value in ViewState
protected string MemberID1Selection
{
get
{
if (ViewState["MemberID1Selection"] != null)
return ViewState["MemberID1Selection"].ToString();
return "";
}
set { ViewState["MemberID1Selection"] = value; }
}
protected string MemberID2Selection
{
get
{
if (ViewState["MemberID2Selection"] != null)
return ViewState["MemberID2Selection"].ToString();
return "";
}
set { ViewState["MemberID2Selection"] = value; }
}
protected string MemberID3Selection
{
get
{
if (ViewState["MemberID3Selection"] != null)
return ViewState["MemberID3Selection"].ToString();
return "";
}
set { ViewState["MemberID3Selection"] = value; }
}
protected void FillddlLocations()
{
FillDropdown(memberID1);
FillDropdown(memberID2);
FillDropdown(memberID3);
memberID1.Visible = true;
memberID2.Visible = true;
memberID3.Visible = true;
}
protected void FillDropdown(DropDownList ddl)
{
using (var connAdd = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"))
{
connAdd.Open();
var sql = "Select policeid from PoliceAccount where status ='available' and handle ='offcase' and postedto='" + ddllocation.SelectedValue + "'";
using (var cmdAdd = new SqlDataAdapter(sql, connAdd))
{
DataSet ds2 = new DataSet();
cmdAdd.Fill(ds2);
ddl.Items.Clear();
ddl.DataSource = ds2;
ddl.DataTextField = "memberID";
ddl.DataValueField = "memberID";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select a Member ID", ""));
ddl.SelectedIndex = 0;
}
}
}
protected void IndexChanged(DropDownList ddlChanged, DropDownList ddlToFilter1, DropDownList ddlToFilter2)
{
string removeValue1 = ddlChanged == memberID1 ? MemberID1Selection : (ddlChanged == memberID2 ? MemberID2Selection : MemberID3Selection);
string selValue2 = ddlChanged == memberID1 ? MemberID2Selection : (ddlChanged == memberID2 ? MemberID1Selection : MemberID1Selection);
string selValue3 = ddlChanged == memberID1 ? MemberID3Selection : (ddlChanged == memberID2 ? MemberID3Selection : MemberID2Selection);
bFlag = false;//Prevent fireing the code again while changing the index
if (removeValue1 != "")
{
ListItem item1 = ddlToFilter1.Items.FindByValue(removeValue1);
ddlToFilter1.Items.Remove(item1);
ListItem item2 = ddlToFilter2.Items.FindByValue(removeValue1);
ddlToFilter2.Items.Remove(item2);
}
if (selValue3 != "")
{
ListItem item3 = ddlToFilter1.Items.FindByValue(selValue3);
ddlToFilter1.Items.Remove(item3);
}
if (selValue2 != "")
{
ListItem item4 = ddlToFilter2.Items.FindByValue(selValue2);
ddlToFilter2.Items.Remove(item4);
}
bFlag = false;
ddlToFilter1.SelectedIndex = ddlToFilter1.Items.IndexOf(ddlToFilter1.Items.FindByValue(selValue2));
ddlToFilter2.SelectedIndex = ddlToFilter2.Items.IndexOf(ddlToFilter2.Items.FindByValue(selValue3));
}
protected void ddlpid1_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID1Selection = memberID1.SelectedValue;
if (bFlag)
{
FillDropdown(memberID2);
FillDropdown(memberID3);
IndexChanged(memberID1, memberID2, memberID3);
}
}
protected void ddlpid2_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID2Selection = memberID2.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID3);
IndexChanged(memberID2, memberID1, memberID3);
}
}
protected void ddlpid3_SelectedIndexChanged(object sender, EventArgs e)
{
MemberID3Selection = memberID3.SelectedValue;
if (bFlag)
{
FillDropdown(memberID1);
FillDropdown(memberID2);
IndexChanged(memberID3, memberID1, memberID2);
}
}
}
I have tested the code and it is working for me. Hope it helps!