asp.net radio buttons show/hide dropdownlist after check/uncheck - c#

I have been trying to create a radio button that shows/hides the two drop-down lists when they are unchecked and checked.
My problem is that whenever I try to check another radio button, the drop-down list for the other radio button does not hide as intended. For example, if I checked rbtnTwocolor, the drop-down list for rbtnOnecolor does not hide.
I wanted to use radio button list but I couldn't insert a drop-down list in between the radio button list items.
<asp:RadioButton ID="rbtnFullColor" Text="Full-Color" runat="server" GroupName="rbtnlistColors" /><br />
<asp:RadioButton ID="rbtnTwoColor" Text="Two-Color" data-toggle="collapse" data-target="#twocolor" runat="server" GroupName="rbtnlistColors" /><br />
<div id="twocolor" class="collapse">
<asp:DropDownList ID="ddlTwoColor" runat="server"></asp:DropDownList>
</div>
<asp:RadioButton ID="rbtnOneColor" Text="One-Color" data-toggle="collapse" data-target="#onecolor" runat="server" GroupName="rbtnlistColors" /><br />
<div id="onecolor" class="collapse">
<asp:DropDownList ID="ddlOneColor" runat="server"></asp:DropDownList>
</div>

for show/hide dropdown when select radiobutton , you can use ways below :
1: use jquery in client side:
<script>
$(document).ready(function () {
$('#rbtnTwoColor').change(
function () {
if ($(this).is(':checked')) {
$('#twocolor').show();
$('#onecolor').hide();
}
});
$('#rbtnOneColor').change(
function () {
if ($(this).is(':checked')) {
$('#onecolor').show();
$('#twocolor').hide();
}
});
});
</script>
2: use server side event (OnCheckedChanged):
markup:
<asp:RadioButton ID="rbtnFullColor" Text="Full-Color" runat="server" GroupName="rbtnlistColors" /><br />
<asp:RadioButton ID="rbtnTwoColor" Text="Two-Color" data-toggle="collapse" data-target="#twocolor"runat="server" GroupName="rbtnlistColors" OnCheckedChanged="rbtnTwoColor_CheckedChanged" AutoPostBack="true" /><br />
<div id="twocolor" class="collapse">
<asp:DropDownList ID="ddlTwoColor" runat="server"></asp:DropDownList>
</div>
<asp:RadioButton ID="rbtnOneColor" Text="One-Color" data-toggle="collapse" data-target="#onecolor" runat="server" GroupName="rbtnlistColors" OnCheckedChanged="rbtnOneColor_CheckedChanged" AutoPostBack="true" /><br />
<div id="onecolor" class="collapse">
<asp:DropDownList ID="ddlOneColor" runat="server"></asp:DropDownList>
</div>
and code behind:
protected void rbtnTwoColor_CheckedChanged(object sender, EventArgs e)
{
ddlTwoColor.Visible = true;
ddlOneColor.Visible = false;
}
protected void rbtnOneColor_CheckedChanged(object sender, EventArgs e)
{
ddlOneColor.Visible = true;
ddlTwoColor.Visible = false;
}
3: use javascript in client side:
add below code to rbtnTwoColor radiobutton
onclick="twoColorClick()"
add below code to rbtnOneColor radiobutton
onclick="oneColorClick()"
now in end of body tag add this code
<script>
function oneColorClick() {
document.getElementById('onecolor').style.display = 'block';
document.getElementById('twocolor').style.display = 'none';
}
function twoColorClick() {
document.getElementById('twocolor').style.display = 'block';
document.getElementById('onecolor').style.display = 'none';
}
</script>
good luck

Related

Maintain collapse state on postback ASP.NET

I have two different forms that collapse and show either one or the other and there's a button to control them.
<div>
<button type="button"
data-toggle="collapse"
data-target=".multi-collapse"
aria-expanded="false"
aria-controls="form1 form2"> Change Form
</button>
<div class="collapse multi-collapse show" id="form1">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" OnClick="SubmitBtn"
<\div>
<div class="collapse multi-collapse" id="form2">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" OnClick="SubmitBtn"
<\div>
</div>
My problem is that whenever theres a post back I lose the collapse state of the forms and it goes back to the form1 showing and form2 hiding.
I want to save the state of the collapsables so they stay the same after a postback and I don't know how to do it.
I have done this through PageRequestManager, of course preserving the state of one or two divs, in your case there are two but if there are more, the solution I give is quite difficult but functional:
ASPX Code:
Add your controls in UpdatePanel
<div>
<button type="button"
data-toggle="collapse"
data-target=".multi-collapse"
aria-expanded="false"
aria-controls="form1 form2"> Change Form
</button>
<asp:UpdatePanel ID="up" runat="server">
<ContentTemplate>
<div class="collapse multi-collapse show" id="form1">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="Ddl1_SelectedIndexChanged"
ID="Ddl1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="Ddl2"
runat="server">
</asp:DropDownList>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="btn1" />
</div>
<div class="collapse multi-collapse" id="form2">
<asp:DropDownList AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
ID="DropDownList1"
runat="server">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2"
runat="server">
</asp:DropDownList>
<asp:Button runat="server" ID="Button2" OnClick="Button1_Click1" Text="btn2" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
JavaScript Code:
The event add_beginRequest is an event that is fired when a Postback starts and it is possible to save the DOM state, while add_endRequest is the event that is fired when the panel is updated and the Postback ends, this is where the controls are arranged according to the conditions:
<script type="text/javascript">
var statusForm1 = false,
statusForm2 = false;
var prm = Sys.WebForms.PageRequestManager.getInstance();
function EndRequestHandler(sender, args) {
if (statusForm1) {
$('#form1').collapse('show');
}
if (statusForm2) {
$('#form2').collapse('show');
}
}
function BeginRequestHandler(sender, args) {
statusForm1 = $('#form1').is(":visible");
statusForm2 = $('#form2').is(":visible");
}
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
</script>
There is a simple and straight forward way of doing this which is, adding the class show to the div that you want to actually show. So, in order to do it, you must set both the divs to run at server. Here is my proposed idea for this problem:
<div class="collapse multi-collapse show" id="myform1" runat="server">
<!-- because in aspx, there is already a form1 form which is parent of all elements that runs at server -->
<!-- Other elements go here -->
</div>
<div class="collapse multi-collapse" id="myform2" runat="server">
<!-- Other elements go here -->
</div>
And on server events, you need to hide and show the respective divs by adding the classes to them.
protected void SubmitBtn1(object sender, EventArgs e)
{
// DoStuff();
ShowMyForm1();
}
protected void SubmitBtn2(object sender, EventArgs e)
{
// DoStuff();
ShowMyForm2();
}
protected void SetDdl2ValuesBasedOnWhatIsSelectedOnDdl1(object sender, EventArgs e)
{
// DoStuff();
// I assume this dropdown is in second form div.
ShowMyForm2();
}
private void ShowMyForm1()
{
myform1.Attributes["class"] = "collapse multi-collapse show"; // this will show the div
myform2.Attributes["class"] = "collapse multi-collapse"; // this will hide the div.
}
private void ShowMyForm2()
{
myform1.Attributes["class"] = "collapse multi-collapse"; // this will hide the div
myform2.Attributes["class"] = "collapse multi-collapse show"; // this will show the div
}
Notice, I have given two events for your submit button because it was appearing on both the forms and it had the same ID for it, which is not allowed for server controls. An ID must be unique. And your form2 has all the elements duplicated in it from the form1
So, to differentiate between those elements, You will have to give them different IDs.

How can I change the color of this 'CheckIn' Button when the ListViewItem is generated?

I would like to have the color of the 'CheckIn' button appear as green depending on the value of some other data in my code but I am unable to access that button outside of its onClick method. I should be able to access it via its ID but for some reason am unable to
<asp:ListView
ID="lvInstructors"
runat="server"
itemwDataBound="lvDataBound"
itemCommand="lvCommand"
Visible="true">
<LayoutTemplate>
<div class="container" id="mainContent">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</div>
</LayoutTemplate>
<ItemTemplate>
<div class="row instructorItem" id="instructorItem">
<asp:HiddenField ID="sessionID" runat="server" Value='<%#Eval("SessionID")%>' />
<asp:HiddenField ID="hasChckedIn" runat="server" Value='<%#Eval("hasCheckedIn")%>' />
<div class="col-2 sessionStartTimeDiv">
<p class="sessionStartTime"><%#Eval("SessionStartTime")%></p>
</div>
<div class="col-2 instructorHeadshotDiv">
<asp:Image class="instructorHeadshot" runat="server" src='<%#Eval("InstructorHeadshot")%>' />
</div>
<div class="col-5 sessionInfoDiv">
<h3 class="instructorName"><%#Eval("InstructorName")%></h3>
<p class="sessionInfo"><%#Eval("SessionInfo")%></p>
</div>
<div class="col-3 checkInBtnDiv">
<asp:Button class="checkInBtn" ID="checkInBtn" runat="server" OnClick="CheckInBtn_Click" Text="Check-In"></asp:Button>
</div>
</div>
<hr />
</ItemTemplate>
<EmptyDataTemplate>
<br />
<br />
No Sessions to Display.
</EmptyDataTemplate>
</asp:ListView>
How I access it in onClick():
protected void CheckInBtn_Click(object sender, EventArgs e)
{
Button checkInBtn = (Button)sender;
checkInBtn.Text = "Check-Out";
checkInBtn.BackColor = Color.Green;
...
}
(Side Question: Why does SelectedIndex return -1 when I click that button ?)
In your itemwDataBound event, look for the value you need then set the button color there. Also you can set the value in the buttons command argument then grab it in the click event.
You need to Access your Button on ItemDataBound event of the ListView to change the color of the Button conditionally.
Here is the link which can help you with this:
datalist itemdatabound event having issues changing item bg color on condition

Clear Specific Textboxes ASPX page

I'm having trouble trying to clear these banking and routing numbers that are in a textbox on an aspx page. I've seen it used where they would just specify the ID of the textbox and do a textbox.text = String.Empty(). But that doesn't seem to work here. Maybe I'm using the wrong ID?? I also tried using JQuery .val("") but that didn't seem to work either.
Here's the code, i'd like to clear both Routing and Account text fields on click of a button:
<div id="DivUser1BankInfo" class="labelAndTextboxContainer">
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelRoutingNumber" runat="server" Text="Routing #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextRoutingNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankRoutingNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<div class="labelContainer">
<asp:Label CssClass="rightFloat" ID="User1LabelAccountNumber" runat="server" Text="Account #:"></asp:Label><br />
</div>
<div class="textboxContainer">
<asp:TextBox ID="User1TextAccountNumber" CssClass="leftFloat " runat="server" Font-Size="Smaller" Width="180px"
Text='<%# Bind("User1BankAccountNumber") %>'
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' /><br />
</div>
<button type="button" id="clearButton1">Clear</button>
<div class="button">
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>' OnClick="clearFields_btn"/><br />
</div>
The OnClick= "clearFields_btn" code behind =
protected void clearFields_btn(object sender, EventArgs e)
{
}
Thanks for any help!
I haven't worked with ASP.NET in a little while, but I think you may want the OnClientClick event, not OnClick. OnClientClick is for client-side code (your jQuery/JavaScript) and OnClick is for server-side code (your C# or VB.NET).
You'd also want your OnClientClick event method to return false, or the server-side code will also fire.
So I think you want something like:
<asp:Button ID="User1ClearBankInfo" runat="server" Text="Reset"
Visible='<%# ApexRemington.BLL.VendorBLL.ShowUser1BankInfo((string)Eval("User1BankInfoEditUser")) %>
OnClientClick="clearText();"/>
And then clearText would look like this:
<script>
function clearText()
{
//our two IDs
$('input[id*="User1TextRoutingNumber"]').each(function(index) {
$(this).val('');
});
$('input[id*="User1TextAccountNumber"]').each(function(index) {
$(this).val('');
});
return false;
}
</script>
EDIT: shoot, I see my mistake. Fixed the code to clear the text of the textbox, not the button ("this").
Edit: removed the space from the "clear" text val.
EDIT: Made search a little more flexible, less dependent on GridView or no GridView.
Try this
<script>
var clear = function(textboxID){$('input[id*=' + textboxID + ']').val('');};
return false;
</script>
<button id="btClearText" onclick="javascript:return clear('txtName');">
but if you need a more specific answer then please post more information
You need something like this. Assuming you want a client side solution (not very clear from your question).
<script type="text/javascript">
function clearTextBox() {
document.getElementById("<%= User1TextRoutingNumber.ClientID %>").value = "";
//or
$("#<%= User1TextRoutingNumber.ClientID %>").val("");
}
</script>
The <%= User1TextRoutingNumber.ClientID %> will ensure you get the correct ID for javascript/jQuery.
A server side solution would be:
protected void clearFields_btn(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tb = GridView1.Rows[i].FindControl("User1TextAccountNumber") as TextBox;
tb.Text = "";
}
}

OnCheckedChanged not called after a postback

I am a new developer and I what I am trying to accomplish is hiding the radio buttons in the bottom DIV and the btnSetFinishState when clicked shows the bottom DIV (which it does from code behind). But the radio buttons when clicked do not fire the code behind method.
Here is .aspx:
<div class="row">
<asp:Button ID="btnSetFinishState" runat="server" Text="FINISHED" OnClick="btnSetFinishState_Click" UseSubmitBehavior="False" Enabled="False" />
</div>
<div class="row" id="finishedBlock" runat="server" visible="false">
<asp:Label ID="lblSetFinishText" runat="server" Text="Are you sure you want to set state to finished?" />
<div data-toggle="buttons" id="divRadioButtons">
<label id="btnFinishyes" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishyes" Text="Yes" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishyes_CheckedChanged" />
</label>
<label id="btnFinishno" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishno" Text="No" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishno_CheckedChanged" />
</label>
</div>
</div>
The aspx.cs code:
protected void btnSetFinishState_Click(object sender, EventArgs e)
{
// if neither radio button clicked
if (!finishyes.Checked && !finishno.Checked)
{
finishedBlock.Visible = true; // show the radio button DIV
//return;
}
}
protected void finishno_CheckedChanged(object sender, EventArgs e)
{
finishedBlock.Visible = false; // hide the radio buttons
finishno.Checked = false; // reset the no button to false
}
protected void finishyes_CheckedChanged(object sender, EventArgs e)
{
// set the finished state code
}
Is there e reason why btnSetFinishState is set to Enabled="False" ?
Because I tested this code and it works
aspx code
<div class="row">
<asp:Button ID="btnSetFinishState" runat="server" Text="FINISHED" OnClick="btnSetFinishState_Click" UseSubmitBehavior="False" Enabled="true" />
</div>
<div class="row" id="finishedBlock" runat="server" visible="false">
<asp:Label ID="lblSetFinishText" runat="server" Text="Are you sure you want to set state to finished?" />
<div data-toggle="buttons" id="divRadioButtons">
<label id="btnFinishyes" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishyes" Text="Yes" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishyes_CheckedChanged" />
</label>
<label id="btnFinishno" class="btn btn-default col-sm-6 col-xs-6">
<asp:RadioButton ID="finishno" Text="No" GroupName="finish" runat="server" AutoPostBack="true" OnCheckedChanged="finishno_CheckedChanged" />
</label>
</div>
</div>
aspx.cs
protected void btnSetFinishState_Click(object sender, EventArgs e)
{
// if neither radio button clicked
if (!finishyes.Checked && !finishno.Checked)
{
finishedBlock.Visible = true; // show the radio button DIV
//return;
}
}
protected void finishno_CheckedChanged(object sender, EventArgs e)
{
finishedBlock.Visible = false; // hide the radio buttons
finishno.Checked = false; // reset the no button to false
}
protected void finishyes_CheckedChanged(object sender, EventArgs e)
{
// set the finished state code
Response.Redirect("WebForm2.aspx");
}
I ran your code in my machine and found event's are firing exactly.
So , I think the different between your environment and mine may be <%# Page directive and missing AutoEventWireup="true" property.
Please share your Asp.net version and project info such as
is there any master pages or not.
UPDATE:
Please create a new sample web form application in visual studio and add a new web form say 'form1', paste your aspx and code behind to the newly added 'form1'. Test and if successfull then check the difference in aspx and code behind with your existing project.Also please let us know.

How can I prevent C# from redrawing a <div> I used jQuery to show

Scenario: I have a modal-style div that will be shown when the user clicks a button. At the time the div is shown, I need to get some data from the back-end to fill in some fields. Additionally, I'd like to use the jQuery method I use for all my modal windows (fades in the modal div, displays a background div as well as enabling the use of ESC key or "click offs" to close the modal).
It looks something like this:
<asp:ScriptManager ID="sc" runat="server" />
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<div class="window">
<h5>Test Form</h5>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="backgroundPopup"></div>
So ... lnkShowIt calls both the jQuery (which will show pnlPopup) as well as the C# (which will populate tbxTime).
jQuery method actually just calls another method from a common js library I have that does the modal window stuff - I don't think that actual code is the problem but here is the simple function used for this page:
<script type="text/javascript" language="javascript">
function showForm() {
loadPopup('#pnlPopup');
}
</script>
Code behind methods look like this:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
}
}
I'm able to generate some level of success by doing the following but it seems like just a major hack and I have to assume there's a better approach:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
}
It seems like it should be easier than this, but the way the UpdatePanel keeps redrawing (and thus resetting the display:none on pnlPopup) is really causing me fits.
Thanks in advance
Solution I just found: putting the LinkButton in its own UpdatePanel and then the form in its own UpdatePanel and making sure the div that is the actual popup box is not in an UpdatePanel at all.
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:UpdatePanel ID="updLink" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<div class="window"style="min-width:500px;">
<h5>Here is a Test Form</h5>
<label>Time:</label>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:Label ID="lblText" AssociatedControlID="tbxText" runat="server" ViewStateMode="Disabled">Text:</asp:Label>
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Panel>
</div>
Seems to do the trick without any Script Registers from the codebehind

Categories