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.
Related
I have a dropdownlist control and a button in asp.net page. The dropdownlist is populated from a method. If I select any item other than the first item, after clicking the button, I lose the selected item in the DDL and it selects the first item and also I am getting the value of the first item only in the button click event. How can I fix the problem?
<asp:DropDownList ID="userDropDown" runat="server" DataTextField="CustomerName" DataValueField="CustomerId">
</asp:DropDownList>
protected void Button1_Click(object sender, EventArgs e)
{
if(!page.isPostBack)
{
userDropDown.DataSource = CC.GetCustomers();
userDropDown.DataBind();
}
}
i think you must have bind userDropDown in Page_Load event without condition
if (!IsPostBack)
Please put dropdown binding part inside if (!IsPostBack) condition then it should work
Please bind dropdownlist values inside the if(!ispostback){} or
after submitting button please bind updated field to dropdownlistname.text
It sounds like you are binding your DropdownList to your datasource at ever request. Instead bind it only if Page.IsPostBack is false like below; (You may not need ObjectDataSource)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//bind your datasource here (something like below)
userDropDown.DataSource = GetCustomers();
userDropDown.DataBind();
}
}
As soon as DataBind() method is called it will lose posted data of that object and the FirstItem will be selected by default.
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.
I have a drop down which has the list of delegates. When the user selects a delegate then I populate the available meet-timings in the second dropdown using the selectedindexchange event of the 1st dropdown
Aspx page
<asp:DropDownList ID="delegate_ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddldelegates_SelectedIndexChanged" Width="200px"></asp:DropDownList>
<asp:DropDownList ID="delegatetime_ddl" runat="server" Width="90px"></asp:DropDownList>
<asp:Button ID="adddelegate" runat="server" Text="Add" onclick="adddelegate_Click"/>
.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds1 = getdata.getdelegatelist();
delegate_ddl.DataSource = ds1.Tables[0];
delegate_ddl.DataTextField = "DELEGATE_NAME";
delegate_ddl.DataValueField = "DELEGATE_ID";
delegate_ddl.DataBind();
delegate_ddl.Items.Insert(0, "--Select--");
}
}
protected void ddldelegates_SelectedIndexChanged(object sender, EventArgs e)
{
string delselection = delegate_ddl.SelectedValue.ToString();
DataSet ds2 = getdata.getdelegatetimelist(delselection);
if (ds2.Tables[0].Rows.Count > 0)
{
delegatetime_ddl.DataSource = ds2.Tables[0];
delegatetime_ddl.DataTextField = "TIMESLOT";
delegatetime_ddl.DataValueField = "TIMEID";
delegatetime_ddl.DataBind();
}
else
{
time_lbl.Text = "No slots Open";
}
}
protected void adddelegate_Click(object sender, EventArgs e)
{
string delegateselected = delegate_ddl.SelectedValue.ToString();
string timeslotselected = delegatetime_ddl.SelectedValue.ToString();
getdata.delegatemeetinsert(personidd, delegateselected, timeslotselected);
}
Now the data gets inserted – but my question here is
As soon as the user click add button I would like to display the delegate selected and the time slot selected in a some sort of a grid view or dynamic table below with a delete option.
Can someone please provide a code sample in C# to achieve the above
Instead of using Gridview for displaying data use some basic control like Labels,it will reduce lot's of unncessary code. use Asp.net 'Panel' control and encapsulate all label and button(for delete purpose) into Panel then hide/show according to need. here is the outline of code that might help you,
if(!page.IsPostBack) // This goes into Page_Load
{
Panel1.Visible=false;
}
protected void adddelegate_Click(object sender, EventArgs e) // add this additional code
{
Panel.Visible=True;
GetDelegate()// This method retrieve the delegate you inserted..
Lable1.Text= "Set here Delegate name you just Retrieved"
Label2.Text="Delegate time you retrived"
}
protected void BtnRemovedelegate_Click(object sender, EventArgs e)
{
string Personidd= retrieve person id
string delegateName= Lable1.text;
String timeslot=Label2.Text
SomeDeleteMethod(personidd, delegateName, timeslot);
Panel1.Visible=false;
}
Hope you get the idea..
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.
I have an asp.net dropDownList which is automatically bound to a sqlDataSource to values of client type on page load. On page load I am also creating a Client object, one of it's properties is ClientType. I am trying to set the SelectedValue of the ddl according to the value of the ClientType property of the Client object unsuccessfully. I recieve the following error message "System.ArgumentOutOfRangeException: 'ddlClientType' has a SelectedValue which is invalid because it does not exist in the list of items". I understand that this is because the list has not yet been populated when I'm trying to set the selected value. Is there a way of overcoming this problem? Thank you!
You have to use the DataBound Event, it will be fired, once databinding is complete
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
// You need to set the Selected value here...
}
If you really want to see the value in the Page load event, then call the DataBind() method before setting the value...
protected void Page_Load(object sender, EventArgs e)
{
DropdownList1.DataBind();
DropdownList1.SelectedValue = "Value";
}
Before setting a selected value check whether item is in list and than select it by index
<asp:DropDownList id="dropDownList"
AutoPostBack="True"
OnDataBound="OnListDataBound"
runat="server />
protected void OnListDataBound(object sender, EventArgs e)
{
int itemIndex = dropDownList.Items.IndexOf(itemToSelect);
if (itemIndex >= 0)
{
dropDownList.SelectedItemIndex = itemIndex;
}
}
EDIT: Added...
If you are doing binding stuff in Page Load, try to follow this way:
Move all binding related code in overriden DataBind() method
In Page_Load of Page add: (in case of control do not call DataBind directrly, this is a responsibility of a parent page)
if (!IsPostBack)
{
Page.DataBind(); // only for pages
}