I have just encountered a strange situation with an ASP.NET page. My form has 2 controls that have AutoPostBack="true": a RadioButtonList and a DropdownList. The RadioButtonList also has EnableViewState="False". When I change the selected item of the dropdownlist, the RadioButtonList SelectedIndexChanged event fires as well. If I remove EnableViewState="False", then this behavior goes away. Can anyone explain why this is happening? I have included sample code below so you can see this behavior for yourself:
<div>
<asp:RadioButtonList ID="rblTest" AutoPostBack="true" OnSelectedIndexChanged="rblTest_SelectedIndexChanged" EnableViewState="false" runat="server">
<asp:ListItem Text="Option 1" Value="1" />
<asp:ListItem Text="Option 2" Value="2" />
<asp:ListItem Text="Option 3" Value="3" />
</asp:RadioButtonList>
<br />
<br />
<asp:DropDownList ID="ddlTest" AutoPostBack="true" OnSelectedIndexChanged="ddlTest_SelectedIndexChanged" runat="server">
<asp:ListItem Text="Select One" Value="" />
<asp:ListItem Text="Option 1" Value="1" />
<asp:ListItem Text="Option 2" Value="2" />
<asp:ListItem Text="Option 3" Value="3" />
</asp:DropDownList>
<br />
<br />
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" Text="Submit" EnableViewState="false" runat="server" />
<br />
<br />
<asp:Label ID="lblResult" runat="server" />
</div>
Here is the code behind code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rblTest.SelectedIndex = 0;
}
}
protected void rblTest_SelectedIndexChanged(object sender, EventArgs e)
{
lblResult.Text += "RadioButton List SelectedIndexChanged fired<br />";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblResult.Text += "Submit Button Click Event Fired<br />";
}
protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
{
lblResult.Text += "Dropdown List SelectedIndexChanged Event Fired<br />";
}
Additionally, if you comment out this line in the code behind:
rblTest.SelectedIndex = 0;
Then this behavior does not occur until you select something from the radio button list. Any help is greatly appreciated.
When you set EnableViewState to false, it means you are not gonna keep the state of the objects. This means that when you do an autopost, the values are reset to their original values.
When it is a post back, you are changing the state of a radio button (rblTest.SelectedIndex = 0) and that's firing the event. So, you change one radio button and 2 events are fired.
Just something else to point out, remember that every time you do a postback, the page is recreated at server-side. And the life-cycle of the page is executed. The ViewState is used on that process to populate the controls. You can read more about it on: https://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx
For me the selectedindexchanged event was firing also when I was not expecting it. What my code did was change the selected value on selectedindexchange event. So, next time when a postback occured, the selectedindexchange event was also fired again. I solved it by first setting the selectedindex to -1 and then setting the actual value.
Initial code was -
protected void rbl_selectedindexchanged(object sender, event evt)
{
rbl.Items.FindByText("something").Selected = true;
}
After modify -
protected void rbl_selectedindexchanged(object sender, event evt)
{
rbl.SelectedIndex = -1;
rbl.Items.FindByText("something").Selected = true;
}
Related
I need to Update a Dropdowlist according to the selected value(s) in a CheckBoxList avoiding the page to reload, I am using an UpdatePanel.
The dropdwonlist should always have an AutoPostback, it should always trigger my "SearchEvent"
I used an UpdatePanel and an AsyncPostBackTrigger on my CheckBoxlist to call the function in code behind to refresh the dropdowlist.
It works only one time. After the first call, I cannot trigger the CheckBoxlist SelectedIndexChanged, instead I get the error :
"Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 404"
My dropdownlist also lose the PostBack, nothing happens.
The View ASPX :
<td>
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:CheckBoxList ID="IsActiveFilterCheck" runat="server" AutoPostBack="true" AppendDataBoundItems="true" CausesValidation="False">
<asp:ListItem Text="Active" Value="1" />
<asp:ListItem Text="Closed" Value="0" />
</asp:CheckBoxList>
</td>
<td>
<asp:UpdatePanel ID="UpdatePanel1" ChildrenAsTriggers="true" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="IsActiveFilterCheck" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<br /><br />
<asp:DropDownList ID="StatusFilterList" runat="server" DataTextField="Name" DataValueField="Id">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</td>
My code behind :
private void Page_Load(object sender, System.EventArgs e)
{
RegisterCallbacks();
if (!IsPostBack)
{
Initialize();
}
}
override protected void OnInit(EventArgs e)
{
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
CheckProfil();
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.SearchButton.ServerClick += new System.EventHandler(this.SearchButton_ServerClick);
this.StatusFilterList.SelectedIndexChanged += new System.EventHandler(this.SearchButton_ServerClick);
this.IsActiveFilterCheck.SelectedIndexChanged += new System.EventHandler(this.IsActiveFilterCheck_Changed);
this.Load += new System.EventHandler(this.Page_Load);
}
protected void IsActiveFilterCheck_Changed(object sender, EventArgs e)
{
// Update the Status Filter List
StatusFilterList.Items.Clear();
if (IsActiveFilterCheck.Items.Cast<ListItem>().Where(li => li.Selected).ToList().Count != 1)
{
BindListInsertAll(StatusFilterList, ExpectedStatusCollection.Instance.GetAll());
}
else
{
IList statusSelected = ExpectedStatusCollection.Instance
.GetAll().Cast<ExpectedStatusDo>()
.Where(exp => IsActiveFilterCheck.SelectedValue == "1" ? exp.Id != 5 && exp.Id != 6 : exp.Id == 5 || exp.Id == 6)
.ToList(); // Only Dead and Signed
// Update the Status
BindListInsertAll(StatusFilterList, statusSelected);
}
UpdatePanel1.Update();
//FindByFilter();
}
When I change the IsActiveFilterCheck checkboxlist I should update only the StatusFilterList as shown in the function IsActiveFilterCheck_Changed, without reloading the full page.
This StatusFilterList should always be able to call/Trigger the event SearchButton_ServerClick
Right now It works only one time when the IsActiveFilterCheck is fired my dropdowlist is updated but after when I click anywhere I get the error and I can't trigger the IsActiveFilterCheck
Take a look to this :
AsyncPostBackTrigger works only the first time
People usually recreates the trigger to work after first time.
I have an asp:checkbox with OnClick="return false" which 'closes' it for changes (that's the nearest equivalent to ReadOnly=true which I found).
I also have a button.
When I click the button I need the codebehind (C#) to change the checkbox to "return true", that is : to 'open' it for checking or unchecking. Clicking the button again should 'close' it back again.
In short - how do I toggle between these two states in the code behind?
HTML:
<asp:Button runat="server" ID="my_Button" Text="click me" OnClick="my_Button_Click" />
<asp:CheckBox runat="server" ID="my_CheckBox" Checked="true" OnClick="return false;" />
Code behind:
protected void my_Button_Click(object sender, EventArgs e)
{
// here is where the toggling should come... <============
}
As you can see here: OnClick vs OnClientClick for an asp:CheckBox? - there's no OnClick for checkbox. You should use OnCheckedChanged instead.
I've attached a minor fix to the problem:
<asp:Button runat="server" ID="my_Button" Text="click me" OnClick="my_Button_Click" />
<asp:CheckBox runat="server" ID="my_CheckBox" Checked="true" OnCheckedChanged="my_checkbox_click" />
And the code behind:
protected void my_checkbox_click(object sender, EventArgs e)
{
}
protected void my_Button_Click(object sender, EventArgs e)
{
my_CheckBox.Enabled = !my_CheckBox.Enabled;
}
In order to achieve this, I added a HiddenField and used it in the code behind.
HTML:
<asp:HiddenField runat="server" ID="my_Hidden_Field" Value="readonly" />
<asp:Button runat="server" ID="my_Button" Text="click me" OnClick="my_Button_Click" />
<asp:CheckBox runat="server" ID="my_CheckBox" Checked="true" OnClick="return false;" />
Code behind:
protected void my_Button_Click(object sender, EventArgs e)
{
if (my_Hidden_Field.Value == "readonly")
{
my_Hidden_Field.Value = "canwrite";
my_CheckBox.Attributes.Add("onclick", "return true;");
}
else
{
my_Hidden_Field.Value = "readonly";
my_CheckBox.Attributes.Add("onclick", "return false;");
}
}
(like always, I look for a solution for a day or two, give up, post a question here, and then I come up with an answer... Hope this will be helpful to others :-)
I need to add a condition to a DropDownList where a method can be executed by button click only if the user has selected a value different than the listItem (default value).
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDataSource5"
DataTextField="proj_name" DataValueField="proj_name">
<asp:ListItem Text="Select a project to clone" Value="" />
</asp:DropDownList>
How can I structure an if condition to validate that the selected value is not the ListItem (default value)?
You can use asp.net delivered validation controls
Ex:
<asp:RequiredFieldValidator id="rfv1"
ControlToValidate="DropDownList1"
Display="Static"
ErrorMessage="* Select a value"
InitialValue="DefaultValueHere"
runat="server"
ValidationGroup="V1"/>
Then edit your button markup to use ValidationGroup
<asp:Button Id="button1" ValidationGroup="V1" .../>
In your codebehind button click code add this
protected void button1_onlick(Object sender, EventArgs e)
{
If(Page.IsValid)
{
// your existing code here
}
}
See sample code below
if (DropDownList1.SelectValue == "")
{
// Write your code here
}
you can also have:
if (DropDownList1.Text == "Select a project to clone")
{
// Write your code here
}
I added a DropDownList from the Toolbox to the Login page on a website I'm working on.
Once I choose a ListItem in the DropDownList (in my case lets say
Gym for example...), when clicked, I want that three bars we'll be opened below my DropDownList(for example, the bars that we'll be opened are Username, Password and ID), I mean three TextBoxes beneath each other.
I think you can either try the SelectedIndexChanged event or Javascript to display the textboxes without a postback.
<select>
<option value="1">Gym 1</option>
<option value="2">Gym 2</option>
<option value="3">Gym 3</option>
<select>
At firest you put your textboxes in a panle then hide this panel and
you should set Autopostback property of you drobdownlist to True and after selecting a item in DropDownList, postback will accur. So you can show that panel include text boxes.
What you might really be needing is dynamic text boxes.
In the html part:
<asp:DropDownList runat="server" ID="DDL1" autopostback = "true" onselectedindexchanged="DDL_SelectChanged" />
<asp:PlaceHolder runat="server" ID="PH1">
</asp:PlaceHolder>
In codebehind:
void DDL_SelectChanged(object sender, EventArgs e)
{
if (DDL1.SelectedIndex == 1)
{
for (int i = 0; i < 3; i++)
{
TextBox newTB = new TextBox();
newTB.ID = "TB" + i;
PH1.Controls.Add(newTB);
}
}
}
You could use MultiveView control. And set active view index in Dropdown's selectedIndexChanged event.
I wrote some example code for you:
ASPx side:
<asp:MultiView ID="multiView" ActiveViewIndex="-1" runat="server">
<asp:View ID="viewGym" runat="server">
<asp:TextBox ID="txtBxUserName" runat="server" />
<asp:TextBox ID="txtBxPassword" runat="server" />
<asp:TextBox ID="txtBxId" runat="server" />
</asp:View>
</asp:MultiView>
<asp:DropDownList ID="Dropdownlist1" runat="server" AutoPostBack="true"
onselectedindexchanged="Dropdownlist1_SelectedIndexChanged">
<asp:ListItem Text="Choose one club" Value="0" />
<asp:ListItem Text="Gym" Value="1" />
<asp:ListItem Text="Shoppers" Value="2" />
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if ( IsPostBack ) //don't forget :)
return;
}
protected void Dropdownlist1_SelectedIndexChanged( object sender, EventArgs e )
{
if ( Dropdownlist1.SelectedValue == "1" ) //Gym item selected
{
multiView.ActiveViewIndex = 0; //Gym view active
}
}
If you want to any view not active when first page load then you set the ActiveViewIndex with -1 in aspx code.
I have 5 radio buttons and a link in my page. Everytime when the linkbutton is clicked, i want my radiobutton to be changed to other. I mean, when a link is clicked, radiobutton check has to move onto rd2 from rd1. Is that possible.
Below is my piece of code for link button and radiobutons.
protected void lnkAddLoc_Click(object sender, EventArgs e)
{
}
<asp:RadioButton ID="rdoLoc1" runat="server" Text="None" TextAlign="left" GroupName="rdoLocation" Checked="true" Width="68px" OnCheckedChanged="rdoLoc1_CheckedChanged" Visible = "true"/>
<asp:RadioButton ID="rdoLoc2" runat="server" Text="1" TextAlign="Left" GroupName="rdoLocation" OnCheckedChanged="rdoLoc2_CheckedChanged" Width="68px" Visible = "true" />
<asp:RadioButton ID="rdoLoc3" runat="server" Text="2" TextAlign="Left" GroupName="rdoLocation" Width="68px" Visible = "true" />
<asp:RadioButton ID="rdoLoc4" runat="server" Text="3" TextAlign="Left" GroupName="rdoLocation" Width="66px" Visible = "true"/>
<asp:RadioButton ID="rdoLoc5" runat="server" Text="4" TextAlign="Left" GroupName="rdoLocation" Width="62px" Visible = "true"/>
protected void lnkAddLoc_Click(object sender, EventArgs e)
{
if (rdoLoc1.Checked)
rdoLoc5.Checked = true;
else if (rdoLoc2.Checked)
rdoLoc1.Checked = true;
else if (rdoLoc3.Checked)
rdoLoc2.Checked = true;
else if (rdoLoc4.Checked)
rdoLoc3.Checked = true;
else if (rdoLoc5.Checked)
rdoLoc4.Checked = true;
}
I'd seriously consider doing this client-side in javascript... a postback everytime you click a link to bump the radio button down? Your users will be extremely annoyed.