I am working on a metrics screen that will display several charts based on different groups in a database. Part of it uses a function that hides selected charts until the user clicks to display them.
The problem is this: I'm using a Databind on the dropdownlist, so every time I select a new group, the page refreshes and everything returns to its default state.
My question is this: Is there a way that I can avoid refreshing the page every time I select a new option from the dropdown list? If so, how? If not, is there a better way to create the dropdownlist and attach values to it? If I set AppendDataBoundItems to false, then I always get the selected value as the first item in the list.
Here's my code for the dropdownlist:
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
Then C# code behind it is this:
public void Page_Load(object sender, EventArgs e){
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
ICollection CreateDataSource(){
DataTable Ministries = new DataTable();
Ministries = oDatabase.GetData(#"SELECT DISTINCT B.Description
FROM tblInvolvement AS A LEFT JOIN tblMinistries AS B
ON A.Activity = B.MinistryID");
DataView dv = new DataView(Ministries);
return dv;
}
Try to use the ASP.NET UpdatePanel. Just wrap your DropDownList in it, and it should works. Here is a quick example that I didn't test.
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="MinistryDropdown" OnSelectedIndexChanged="Selection_Change" AutoPostback="true" AppendDataBoundItems="true" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>
On a final note, you will soon find out the limits of this solution, and later you might prefer to use Javascript instead.
I think the issue is that you are rebinding the data on Page_Load but you are not checking if !IsPostBack in other words, your code should look like this:
public void Page_Load(object sender, EventArgs e){
if(!IsPostBack)
{
MinistryDropdown.DataSource = CreateDataSource();
MinistryDropdown.DataTextField = "Description";
MinistryDropdown.DataValueField = "Description";
MinistryDropdown.DataBind();
...other code here...
}
}
Related
I can't get the dropdown onselectedindexchanged event to fire, and when I make a selection it resets the value of the dropdown onpostback, even though I have the if (!ispostback) in the page load event.
this is a content page in a master page in asp in case that matters.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server"
EnableViewState="true"
OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged"
AutoPostBack="true"></asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection constr = new SqlConnection(ConfigurationManager.ConnectionStrings["CBTestDBConnectionString"].ConnectionString);
SqlCommand eventsvcprogCMD = new SqlCommand("select*from SvcProg where eventatteligable=1", constr); // table name
SqlDataAdapter eventsvcadapt = new SqlDataAdapter(eventsvcprogCMD);
DataSet eventsvcset = new DataSet();
constr.Open();
eventsvcadapt.Fill(eventsvcset); // fill dataset
EventSVCProgList.DataTextField = eventsvcset.Tables[0].Columns["SvcProgID"].ToString(); // text field name of table dispalyed in dropdown
EventSVCProgList.DataValueField = eventsvcset.Tables[0].Columns["eventatteligable"].ToString();
EventSVCProgList.DataSource = eventsvcset.Tables[0]; //assigning datasource to the dropdownlist
EventSVCProgList.DataBind(); //binding dropdownlist
constr.Close();
}
}
protected void EventSVCProgList_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Eat Poop");
var somevalue = EventSVCProgList.SelectedValue;
}
There are couple of things.
1) You need to add a Script Manager to the page at the top if not added already(it will give you a runtime error if you have not added a script Manager to the page)
2) You need to change the Update Panel content as shown below
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList ID="EventSVCProgList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="EventSVCProgList_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="EventSVCProgList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
There seems that any parent control or page leven ViewState is disabled. please check in debug mode that what value you getting for EventSVCProgList.EnableViewState and other parent controls' as well.
thanks for the help. its still not working so i'm just going to try to use javascript instead. its got to be some fundamental flaw with the way the master page or content page is setup.
I'm trying to populate a dropdownlist with an objectdatasource programatically. It's a user control, so in my ascx I have this:
<asp:ObjectDataSource ID="odsFicheros" runat="server"
OldValuesParameterFormatString="original_{0}"
onselecting="odsFicheros_Selecting" SelectMethod="ejecutaconsultaFicheros" TypeName="DatosGW.ControlBuscador">
</asp:ObjectDataSource>
<asp:DropDownList ID="cmbFicheros" runat="server" CssClass="form-control"
DataTextField="fichero" DataValueField="fichero" DataSourceID="odsFicheros"
ondatabound="cmbFicheros_DataBound" AutoPostBack="True"
onselectedindexchanged="cmbFicheros_SelectedIndexChanged">
</asp:DropDownList>
On the code behind I do this:
protected void Page_Load(object sender, EventArgs e)
{
odsFicheros.TypeName = "DatosGW.ControlBuscador";
odsFicheros.SelectMethod = "ejecutaconsultaFicheros";
Parameter consultas = new Parameter(consulta, TypeCode.String);
odsFicheros.SelectParameters.Add(consultas);
odsFicheros.DataBind();
cmbFicheros.DataSource = odsFicheros;
this.ejecutarConsulta();
}
And finally on my ControlBuscador class I have the method which returns a datatable, but it doesn't work, why?. If you need more details, please let me know it.
In Visual Studio, I did this with the wizard on the Selectin property:
e.InputParameters["consulta"] = hfConsulta.Value;
I created a HiddenField with the parameter I want, so now it's working
I filled a dropdownlist with active directory users, not a big deal and works great. The problem is it's setting <option selected="selected" value="user">User</option>
on the first one and won't let me change it in the code behind. Is there a way to keep it from automatically setting that selected="selected"?
<asp:DropDownList ID="dlst" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dlstvalues" DataTextField="name"
AppendDataBoundItems="true">
<asp:ListItem>-- Select --</asp:ListItem>
</asp:DropDownList>
Or this should work:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList1.SelectedIndex = 0;
}
}
It will automatically set the first one as selected. You have to enter a default value into the drop down list and set it to the first item.
ddlName.Items.Insert(0, new System.Web.UI.WebControls.ListItem("<--Select-->", "0"));
This is happning because you may be binding your dorpdown on page load.
And you may not be checking for postback
Doing so it will bind the values again and you will get the new items in the dropdown list.
The previous selected index will not remain.
You should bind this in !isPostBack
if (!Page.IsPostBack)
{
//bind data
}
I have the following markup / code block in the ASPX file.
The binding of the ddl is triggered after Page_Load event which is in the code behind file.
This results me not able to get the selected value of the dropdownlist if I were to use such flow.
However for some purpose I require it to work this way.
Any idea how I could get the dropdownlist selected value when a post back is being triggered (click of the button)?
Page URL: page.aspx?para1=0¶2=value
ASPX PAGE
<%
if (Convert.ToInt32(Request.QueryString["para1"]) == 0)
{
ddl.DataValueField = "value";
ddl.DataTextField = "text";
ddl.DataSource = ds; //ds is valid, exact code not shown
ddl.DataBind();
} else {
//write in this area
Response.Write("Not 0");
}
%>
<form runat="server" id="user_form" class="form-horizontal">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:UpdatePanel ID="updPanel" runat="server">
<ContentTemplate>
<asp:DropDownList runat="server" ID="ddl">
</asp:DropDownList>
<%-- this button will call btnSave_Click to get the ddl's value--%>
<asp:Button runat="server" ID="btn" Text="Button" OnClick="btn_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//do my stuff
}
}
protected void btn_Click(object sender, EventArgs e)
{
int intValue = Convert.ToInt32(ddl.SelectedValue);
//do my stuff
}
The ASPX Page code block will run after Page_Load / page's lifecycle, then will determine what to do base on the url parameters.
Thanks in advance!
You could always throw in a hidden object and use jquery to copy the value to the hidden value based on a certain action without a postback and would do it client side like it sounds like you want it to do
I have the following code in my aspx page:
<asp:Button id="display_button" runat="server" Text="Display" OnClick="Button1_Click" />
<asp:Button id="edit_button" runat="server" Text="Edit" OnClick="Button2_Click" />
<asp:Button id="save_button" runat="server" Text="Save" OnClick="Button3_Click" Visible="false" />
<asp:MultiView id="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View id="View1" runat="server">
<asp:FormView id="view_program" runat="server">
<ItemTemplate>
<%# Eval("status").ToString().Trim() %>
</ItemTemplate>
</asp:FormView>
</asp:View>
<asp:View id="View2" runat="server">
<asp:FormView id="edit_program" runat="server">
<ItemTemplate>
<asp:DropDownList id="p_status" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:FormView>
</asp:View>
</asp:MultiView>
and the following functions attached to the buttons in the code-behind page:
protected void Button1_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View1);
save_button.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View2);
save_button.Visible = true;
}
protected void Button3_Click(object sender, EventArgs e)
{
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
var status = p_status.SelectedValue;
Label1.Text = status;
//save_button.Visible = false;
//MultiView1.SetActiveView(View1);
}
The idea being, that there are two views, the first displays the information, if the user wants to edit the information, they click button 2 which changes the view to the edit mode, which has the controls (drop downs, text fields, etc). It also makes the 'save' button appear.
What I am trying to make happen is, when the save button is clicked, it will grab all of the values from the various fields, update the object and then update the database. Then it would flip back to view1 with the updated info.
Problem is, as you can see in void Button3_Click, I try grab the values from the control, p_status, but it only gets the original value. example, the menu has three values, 'Green', 'Yellow', and 'Red'. Green is the default value and is selected when view2 is displayed. However, if I select Yellow or Red, and click save, rather than the label being updated to display one of those two values, it always displays Green.
Any ideas?
edit: page load function per request below
protected void Page_Load(object sender, EventArgs e)
{
try
{
Person myPerson = new Person(userid);
TestProgram myProgram = new TestProgram(id);
List<TestProgram> program = new List<TestProgram> { myProgram };
view_program.DataSource = program;
view_program.DataBind();
edit_program.DataSource = program;
edit_program.DataBind();
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
p_status.Items.Add(new ListItem("Green", "Green"));
p_status.Items.Add(new ListItem("Yellow", "Yellow"));
p_status.Items.Add(new ListItem("Red", "Red"));
//myProgram.Status = "Red";
p_status.SelectedValue = myProgram.Status;
}
catch (Exception ex)
{
Response.Write(ex);
Label1.Text = ex.ToString();
}
}
Whoops...missed a little someting.. my
bad
when asp.net is not behaving as expected this is your best friend: MSDN: ASP.NET PAGE LIFECYLE
Upon Further Review...
there are a couple of problems here. your drop down list control with an id of "p_status" is contained inside a multiview (I forgot about what that meant...) you need to move the code to populate p_status into pre-render after checking to see if Multiveiw1.ActiveView = View2. Since it will always be a post back you need to bind values late in the page cycle