Building dynamic DropDownList with Event Handling - c#

I want to build a dynamic DropDownList and add some list item.
With below code I can do it.
protected void BuildDynamicDropDown()
{
DropDownList ddl = new DropDownList();
ddl.ID = "newDDL";
ddl.SelectedIndexChanged += dynamicDDL_SelectedIndexChanged;
ddl.Items.Add(new ListItem("stack1", "stack1"));
ddl.Items.Add(new ListItem("stack2", "stack2"));
ddl.Items.Add(new ListItem("stack3", "stack3"));
ddl.AutoPostBack = true;
Panel1.Controls.Add(ddl);
}
protected void dynamicDDL_SelectedIndexChanged(object sender, EventArgs e)
{
//this part of code should trig another dynamic dropdown
}
But I want to use that SelectedIndexChanged event in order to change another dynamic dropdown value.
Do you have any idea?
At this link how to create event handler for dynamic drop down list in c#
one solution likes below
ddlFilter.SelectedIndexChanged += new EventHandler(ddl2_SelectedIndexChanged);
ddlFilter.AutoPostBack = true;
void ddlFilter_SelectedIndexChanged(object sender, EventArgs e)
{
//your code
}
Shortly,
I want to build more than one dynamic dropdown and assume that 3 dropdown and I want to handle their selectedindexchange events in order to interact between themselves.

If i m getting your Query!!
You can use Items array of dropdownlist and loop through it and check the condition and do the changes in the items list of another dropdownlists on selected index changed.

Related

SelectIndexChanged doesn´t work in dynamic drop down list

I working with ASP.NET WebForms with C#. I have a button when clicking on it creates a dropdownlist. This list is created in the "createlist" method with parameters such as id and items. I also add a SelectedIndexChanged event handler.
The list is created successfully, but when I switch between the 3 options the handler is not firing, because the console never prints the message "CHANGE".
Here's my code:
namespace web
{
public partial class Default : System.Web.UI.Page
{
List<string> lstDivs = new List<string>();
protected void btn_Click(object sender, EventArgs e)
{
Control results = FindControl("results");
lstDivs.Add("One");
lstDivs.Add("Two");
lstDivs.Add("Three");
DropDownList lstTipo = createList("lstTipos", lstDivs);
results.Controls.Add(lstTipo);
}
public DropDownList createList(string id, List<string> lstStr)
{
DropDownList lst = new DropDownList();
lst.Attributes.Add("runat", "server");
lst.ID = id + "" + Variables.numDiv;
lst.SelectedIndexChanged += new EventHandler(change);
lst.AutoPostBack = true;
lst.Items.Add(new ListItem("Select...", "Select..."));
for (int i = 0; i < lstStr.Count; i++)
{
lst.Items.Add(new ListItem(lstStr[i], lstStr[i]));
lst.Items[i].Attributes.Add("id", lst.ID + "" + i.ToString());
}
return lst;
}
protected void change(object sender, EventArgs e)
{
Debug.Write("CHANGE\r\n");
}
}
}
Once a dynamic control is created and displayed to the user, it has to be recreated on a postback for its events to fire. Execution of events is triggered by the control itself, hence, if there is no control - there is nobody to detect the change and call your change method.
You have to persist the fact that the dropdown has been created (hidden field, ViewState, Session, database, ...) and create it again in Page_Load.
I'm not sure your control exists on the postback since it is dynamically created. I found this post which might be helpful:
Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event
Also, I don't think you need to add the runat as an attribute. This should be done automatically.

Dynamic controls ASP.NET

In web page, created controls dynamically and when select dropdown item ddl do not remember selected item
example
protected void Page_Init(object sender, EventArgs e)
{
// create
DropDownList ddl = new DropDownList();
ddl.SelectedIndexChanged += new EventHandler(ddl_selectedIndexChanged);
ddl.AutoPostBack = true;
//....
Page.Controls.Add(ddl);
// Fill dropdownlist when page loaded first time
ddl.DataSource = LoadFormDataBase;
ddl.DataBind();
}
protected void ddl_selectedIndexChanged(object sender, EventArgs e)
{
//
}
When selected dropdown item web page recreated and my selected item disappear, ViewState do not work. This dynamic controls often used and I have an doubt to use Session?
Follow the below way:
http://www.codeproject.com/Articles/502251/How-to-create-controls-dynamically-in-ASP-NET-and
You need to handle viewstate carefully.

trigger an eventhandler on postback c#

I am pretty new to c# programming.
I have an issue that follows:
I have a GridView on a web form, a DropDownList and a Label control. When i select a value from a DDL a Grid View is populated with rows from the database that equal the DDL condition(in my case DDL represent Countries, GV lists the Cities).
When i delete the last City from a GV using a built in GV Delete function i would like to automatically write in a Label that there are no more Cities in selected Country.
How can i achieve that?
I tried to put
protected void GridView1_RowDeleted1(object sender, GridViewDeletedEventArgs e)
{
if (GridView1.Rows.Count == 0)
{
LabelGrid.Text = "No more cities.";
}
}
but it didn't work.
Thanks for your help
Consider using PreRender event, when that event runs the Row.Count property contains the correct value. (decremented after delete)
protected void GridView1_PreRender(object sender, EventArgs e)
{
if (GridView1.Rows.Count == 0)
{
LabelGrid.Text = "No more cities.";
}
}

Catch dropdown selected text inside a repeater

I have dropdownlist inside a repeater and whenever the selected text is changed i have to show it in a textbox how can i do this??
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("DropDownList6");
TextBox txt = (TextBox)e.Item.FindControl("TextBox4");
txt.Text = ddl.SelectedItem.Text;
}
First, don't use ItemCreated therefore since it triggered too early in the life-cycle(for the ViewState). You would also have to check for the ItemType first.
Instead use the DropDownLists SelectedIndexChanged event directly:
protected void Ddl_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList) sender;
RepeaterItem item = (RepeaterItem) ddl .NamingContainer;
TextBox txt = (TextBox) item.FindControl("TextBox4");
txt.Text = ddl.SelectedItem.Text;
}
you could add appropriate OnSelectedChange (somwthing) event handler to the DropDownList and then when event fired you catch it and do whatever you want , you can do it in both client side or server side .
You will need to use the add a handler to associate each dropdown control with the appropriate event handler. I don't have VS in front of me but it should be something like:
txt.SelectedIndexChanged += new EventHandler(YourMethodName)

Dynamically Created DropDownList within a List of Panels is not allowing for Event Handling

I am trying to create a UI that creates rows that can be dynamically populated.
I am at the point where I can add a Panel to my list that contains a DropDownList and has an associated Remove Button.
The Remove Button has an OnClick event bound that allows me to remove that specific panel.
I am having an issue when trying to bind a SelectedIndexChanged EventHandler to my DropDownList it does not.
I suspect this had something to do with how I am recreating my controls after every Postback.
I am not asking for or expecting a straightforward "Add this or Change this in the code." I really want to have a understand where I am going wrong, sorry for asking so much! :s
protected void Page_Load(object sender, EventArgs e)
{
//Showing this for the the poster that asked.
if (!IsPostBack)
{
GetClustersFromDB(user);
BindGrid();
BindState();
}
if (Session["persistControls"] != null)
{
persistControls = (List<Panel>)Session["persistControls"];
int count = 0;
foreach (Panel dynamicControl in persistControls)
{
DropDownList list = new DropDownList();
list.ID = "list" + count;
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
list.AutoPostBack = true;
list.Items.Add(new ListItem("", "0"));
list.Items.Add(new ListItem("Title", "1"));
dynamicControl.ID = "panel" + count;
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = count.ToString();
myPlaceholder.Controls.Add(dynamicControl);
myPlaceholder.Controls.Add(btnRemove);
count++;
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
DropDownList list = new DropDownList();
list.SelectedIndexChanged += new EventHandler(list_SelectedIndexChanged);
list.AutoPostBack = true;
list.Items.Add(new ListItem("", "0"));
list.Items.Add(new ListItem("Title", "1"));
Panel panelContainer = new Panel();
panelContainer.ID = "panel" + persistControls.Count;
panelContainer.Controls.Add(list);
Button btnRemove = new Button();
btnRemove.Click += new EventHandler(btnDelete_Click);
btnRemove.Text = "Remove";
btnRemove.CommandArgument = persistControls.Count.ToString();
myPlaceholder.Controls.Add(panelContainer); // Pushes the Panel to the page.
persistControls.Add(panelContainer);// Adds our Panel to the Control list
myPlaceholder.Controls.Add(btnRemove); // Pushes our Button to the page.
Session["persistControls"] = persistControls; // put it in the session
}
catch
{
throw;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
int deleteThisOne = int.Parse(((Button)sender).CommandArgument);
persistControls.Remove(persistControls[deleteThisOne]);
Session["persistControls"] = persistControls;
Response.Redirect(Request.Url.ToString());
}
catch
{
throw;
}
}
protected void list_SelectedIndexChanged(object sender, EventArgs e)
{
throw new NotImplementedException();
}
//aspx File Snippets
<asp:Button ID="btnAdd" runat="server" Text="Add Control" onclick="btnAdd_Click" />
<asp:Button ID="btnClear" runat="server" Text="Reset" onclick="btnClear_Click"/>
<asp:PlaceHolder ID="myPlaceholder" runat="server"></asp:PlaceHolder>
Maintaining controls like this is a real pain. You could try an alternative approach:
Create a (small) class that encapsulates the data you want to display in each Panel.
Maintain a List of these objects in Session.
Use an <asp:Repeater> to display the items by data-binding it to your list.
In the repeater's ItemTemplate, you can write out your <asp:Panel> that can contain a <asp:DropDownList>. Use the ItemCommand property of the drop-down list to bind it to a server-side event handler. Similarly you can put an <asp:Button> in the template and bind the ItemCommand property of this to another server-side event handler.
When you click Add, you'll postback to the server, add to your list, save it in session, re-bind the repeater.
When you click a Remove, you'll postback to the server, remove the item from your list, save it in session, re-bind the repeater.
This way lets ASP.Net handle all the control creation for you. However, if you really want to do all that yourself, then this Infinities Loop blog post is required reading.
I don't think this will work. If you create the dropdownlists in the PageLoad event, the viewstate will never get bound to it, and you will never see the option selected by the user.
You should create the controls OnInit, then when the PostBack occurs the ViewState data will get bound to the control and you will be able to access it.

Categories

Resources