One checkBox to be checked - c#

I have the following checkBox function in a gridView-
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" OnCheckedChanged="CheckBoxPN_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
Which creates a checkBox for every row created in the gridView.
My problem being that in the event-
protected void CheckBoxPN_CheckedChanged(Object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow row = (GridViewRow)chk.NamingContainer;
int gID = System.Convert.ToInt16(row.Cells[1].Text);
gridViewDataSource.SelectCommand = sqlCommand + gID;
}
I am using this to retrieve values. How ever once a user checks a checkBox, then goes to check another one, the previous checkBox state is still checked.
How can I modify the code to uncheck the last checkBox when the new one is checked?
EDIT
#Neil Knight 's answer implements the correct functionality, however as I am using the checked_changed event, when the new checkBox is getting checked, this fires the event, and gets the correct answer. However when the previous checkBox gets unchecked, this again fires the event and gets the wrong answer. How can I stop the gID value getting replaced with the old answer?

ASP.Net example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>checkboxes</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
<script language="javascript">
function SingleSelect(regex,current)
{
re = new RegExp(regex);
for(i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i];
if (elm.type == 'checkbox') {
if (re.test(elm.name)) {
elm.checked = false;
}
}
}
current.checked = true;
}
</script>
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="100%" align="center">
<tr>
<td>
<br/>aaaa<input type="checkbox" id="chkOne" name="chkOne"
value="aaaa" checked onclick="SingleSelect('chk',this);" />
<br/>bbbb<input type="checkbox" id="chkTwo" name="chkTwo"
value="bbbb" onclick="SingleSelect('chk',this);" />
<br/>cccc<input type="checkbox" id="chkThree" name="chkThree"
value="cccc" onclick="SingleSelect('chk',this);" />
<br/>dddd<input type="checkbox" id="chkFour" name="chkFour"
value="dddd" onclick="SingleSelect('chk',this);" />
<br/>eeee<input type="checkbox" id="chkFive" name="chkFive"
value="eeee" onclick="SingleSelect('chk',this);" />
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</form>
</body>
</HTML>
Taken from Stephen Cheng's answer.

You can use a radio button as suggested by X.L.Ant (do remember to make them into the same group(you do this with GroupName="FOO" property of radio buttons))
alternatively(if Checkbox is what you really want to use)
you can unset all the CheckBoxes, except the one selected(which is terribly slow).
<ItemTemplate>
<asp:RadioButton ID="chkRow" runat="server" OnCheckedChanged="CheckBoxPN_CheckedChanged" AutoPostBack="true" GroupName="foo"/>
</ItemTemplate>

Related

set the visibility of text box to false when the rad combo box shows empty message string

I have a user control in which am using one editable rad combo and one rad text box. depends on the value of combo i need to set the visibility of text box. its working. the code is as follows.
1. User Control
<asp:Panel ID="pnl44" runat="server" Visible="false">
<table width="100%">
<tr>
<td style="width: 20%;">
Quantity<span style='color: red'>* </span>
</td>
<td align="left" style="vertical-align: top; width: 80%;">
<table width="100%">
<tr>
<td align="left" style="vertical-align: top; width: 63%;">
<telerik:RadComboBox ID="pnl44_ddlUnit" runat="server" DropDownAutoWidth="Enabled"
Width="150px" AutoPostBack="true" OnSelectedIndexChanged="ddlUnit_SelectedIndexChanged"
EmptyMessage="---Select---" markfirstmatch="True" allowcustomtext="false" onclientblur="OnClientBlurHandler"></telerik:RadComboBox>
</td>
<td>
<asp:TextBox ID="pnl44_txtQuantity" MaxLength="10" runat="server" CssClass="textfield"
Width="145px" />
<ajaxtoolkit:FilteredTextBoxExtender ID="ftetxtQuantity" FilterType="Numbers" runat="server"
TargetControlID="pnl44_txtQuantity" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</asp:Panel>
in the code behind am handling the selected changed event to set the visibility, its working fine. the javascript for on blur is as follows (it is in the aspx page).
<script type="text/javascript" language="javascript">
function OnClientBlurHandler(sender) {
var item = sender.findItemByText(sender.get_text());
if (!item) {
sender.clearSelection();
}
}
</script>
with this whenever the combo value is null, it will show the empty message.
the scenario is like this
by default the visibility of txtQuantity is false.
when user select 'value1' from combo, the txtQuantity visibility is true;
then the user is deleting value1 using delete/backspace, combo box will show empty message string, but that time the txtQuantity visibility is true, instead false.
please help me to solve the issue...
It seems you change the textbox visibility on the server, so you would need to initiate a request that will do that for you when you clear the combo selection. Basics:
function OnClientBlurHandler(sender) {
var item = sender.findItemByText(sender.get_text());
if (!item) {
sender.clearSelection();
__doPostBack("", "");
}
}
which will generate a generic postback. You can use hidden buttons or hidden fields or other arguments to know where this postback originated from.
Option 2: hide the textbox with JavaScript, e.g.:
function OnClientBlurHandler(sender) {
var item = sender.findItemByText(sender.get_text());
if (!item) {
sender.clearSelection();
document.getElementById("<%=pnl44_txtQuantity.ClientID%>").style.display="none";
}
}
or something similar, depending on what the ACT control does with the textbox.

How do I validate multiple asp.net checkboxes in C#

I have spent a lot of time trying to get 4 checkboxes to validate in a web application. This web app has already been written, and uses checkboxes when it probably should use a checkboxlist. However, I believe it will be an inordinate amount of work to change all of the existing code, so being able to validate the existing 4 boxes would save me a total re-write.
I have been through stackoverflow looking for the answer for two days, and I found several answers that will help me if I have a single checkbox, but I can't get anything to work if I have multiple, and I just want to validate a single box.
Below is the checkbox info for the ascx form:
</asp:Panel>
<cc1:PopupControlExtender ID="PopupControlExtender1" PopupControlID="PanelTypeOwnership"
runat="server" TargetControlID="helpTypeOwnership" Position="Left">
</cc1:PopupControlExtender>
<strong> Type of Ownership:</strong></td>
<td class="style12">
</td>
<td class="style11">
</td>
<td>
<strong>
<div class="textBoxImg" id="helpTypeOwnership" runat="server" style="width: 24px;
float: right;">
</div>
</strong>
</td>
</tr>
<tr>
<td style="padding-left: 2px;" class="style2">
<asp:CheckBox ID="chbAgricultural" runat="server" CssClass="texLabel" Text=" Agricultural/Horticultural Society"
BorderStyle="None" Width="260px" />
</td>
<asp:CustomValidator runat="server" ID="validateCheckBoxes" EnableClientScript="true"
OnServerValidate="validateCheckBoxes_ServerValidate"
ClientValidationFunction="validateCheckBoxes_ServerValidate">Please select a type of ownership.</asp:CustomValidator>
<td valign="middle" align="left" class="style10">
<asp:CheckBox ID="chbEnducational" runat="server" CssClass="texLabel"
Text=" Educational" />
</td>
<td class="style12">
<asp:CheckBox ID="chbReligious" runat="server" CssClass="texLabel"
Text=" Religious" />
</td>
<td class="style11">
<asp:CheckBox ID="chbCharitable" runat="server" CssClass="texLabel"
Text=" Charitable" />
</td>
</tr> </table>
<div style="height: 39px;">
</div>
The code relating to the checkbox validation on the ascx.cs form is:
protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
if (!chbAgricultural.Checked && !chbEnducational.Checked && !chbReligious.Checked && !chbReligious.Checked)
args.IsValid = false;
else
args.IsValid = true;
}
The code for the submit button is:
protected void lbnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
MembershipUser mUser = Membership.GetUser(Page.User.Identity.Name);
if (mUser == null) return;
DateTime dateT = Convert.ToDateTime(TextBoxDateWrite.Text);
FairShareApplication451a.changeStatusToVoid(new Guid(mUser.ProviderUserKey.ToString()), GetParcelId());
FairShareApplication451a apl451a = FairShareApplication451a.CreateApplication451a(new Guid(mUser.ProviderUserKey.ToString()),
lblNumberApplication.Text, TextBoxCounty.TextBoxText, TextBoxTaxyear.TextBoxText, TextBoxContactName.TextBoxText, TextBoxContactPhone.TextBoxText, TextBoxStateIncorporated.TextBoxText, //
GetParcelId(), chbAgricultural.Checked, chbEnducational.Checked, chbReligious.Checked, chbCharitable.Checked, TextBoxOrganizationName.TextBoxText, TextBoxPropOwnerName.TextBoxText,//
TextBoxMailingAddress.TextBoxText,
TextBoxCity.TextBoxText, DDListControl2.SelectedValue, TextBoxZipCode.TextBoxText, //TextBoxState.TextBoxText
TextBoxPropertyDescriptions.TextBoxText,
TextBoxAuthorizedSignature.Text, TextBoxTitle.Text, dateT, "Not Reviewed",
PropertyAddress.TextBoxText, PropertyCity.TextBoxText, PropertyState.SelectedValue, PropertyZip.TextBoxText); // Convert.ToDateTime(TextBoxDateWrite.Text)
//save uploaded files
SaveUploadedFiles(apl451a.Id);
FileUploader1.ResetControl();
MailSend m_snd = new MailSend(Server, Request);
m_snd.SendMessage(apl451a.UserId, FairShare.MailSend.mailType.received);
Response.Redirect("~/securezone/CurrentApplications.aspx");
// ClearAll();
}
}
I am sure I am missing something. I am still able to submit forms without checking any boxes. Any help would be greatly appreciated.
Note: I am aware educational is spelled incorrectly. I inherited this site --I just haven't gotten around to changing it in all of the relevant places.
Another option is to create a property on the ASCX user control
public bool IsOneCheckboxChecked
{
get
{
return (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked);
}
}
You can then remove this method: (and maybe avoid a postback in the process)
protected void validateCheckBoxes_ServerValidate
and when it is time to submit the form, check:
if (userControlInstance.IsOneCheckboxChecked)
{
// good to go.
}
To check if one or more of the checkboxes is checked, you just need
args.IsValid = (chbAgricultural.Checked || chbEnducational.Checked || chbReligious.Checked || chbCharitable.Checked)
(you had chbReligious in there twice).
And I'm fairly sure you need to tie the CustomValidator to a Control to check, unless there is something else in the page which isn't shown.
Why to give up with client side validation? In your CustomValidator you have:
OnServerValidate="validateCheckBoxes_ServerValidate"
and
ClientValidationFunction="validateCheckBoxes_ServerValidate"
You have ClientValidationFunction pointing to the same server function. Try something like the following:
ClientValidationFunction="validateCheckBoxes_CLIENTValidate"
Being the client function something like this:
<script type="text/jscript">
function validateCheckBoxes_CLIENTValidate(sender, e) {
e.IsValid = jQuery(".texLabel input:checkbox").is(':checked');
}
</script>
If you cannot resolve multiple checkbox values by css class name you can take a look to this link

How to show/hide a nested list using JavaScript in ASP.NET?

Edit: Found the solution, and posted the answer below.
In my ASP.NET c# project, I have a ListView (ParentList) bound to a DataSource. Within the ParentList, inside the ItemTemplate, I have another Repeater (ChildList) bound to an attribute of each ListViewDataItem.
<asp:ListView ID="ParentList" runat="server" DataSourceID="objectDataSourceID" DataKeyNames="ID">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Attribute1") %>' />
</td>
<td valign="top">
<asp:Repeater ID="ChildList" runat="server" DataSource='<%# Eval("Attribute2ReturnsAnotherList") %>'>
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<%# DataBinder.Eval(Container.DataItem, "childAttribute") %>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
...
</LayoutTemplate>
</asp:ListView>
The code above works just fine, everything renders great. Now I want to add a link that will show/hide the ChildList. Something like the below:
<td valign="top">
<a href="javascript:ToggleListVisibility()" >Show/Hide</a>
<asp:Repeater ID="ChildList" runat="server" DataSource='<%# Eval("Attribute2ReturnsAnotherList") %>'>
</asp:Repeater>
</td>
How can I achieve this? I can't just use getElementById as I normally would, as the ul lists are within a Repeater nested inside the ListView. I tried obtaining the parentNode, then accessing the children and toggling the visibility of the ul element within:
function ToggleListVisibility(source) {
var childrenlist = source.parentNode.children;
for (var i = 0; i < childrenlist.length; i++) {
if (childrenlist[i].tagName == 'ul') {
if (childrenlist.style.display == "none") {
childrenlist.style.display = "block";
} else {
childrenlist.style.display = "none";
}
}
}
}
<a href="javascript:ToggleListVisibility(this)" >Show/Hide</a>
but that didn't work. IE's 'error on page' gave me this error:
The parentNode is null or not an object.
I also tried setting the a runat="server" attribute to my ul element, then using <%# ulID.ClientID %> to pass the ul id to the Js function, but visual studio complained:
Server elements cannot span templates.
Finally, I tried just passing the ul object into the Js function, like this:
function ToggleListVisibility(src) {
if (src.style.display == "none") {
src.style.display = "block";
} else {
src.style.display = "none";
}
}
<a href="javascript:ToggleListVisibility(ulID)" >Show/Hide</a>
...
<ul id="ulID">
which works, but it toggles the visibility for the ChildList in all rows within my ParentList. I want it to only toggle the visibility for the ChildList in its own row.
I'm at a loss of what to do. JavaScript is not my forte, and I would appreciate if someone can provide some pointers. Thanks in advance.
Ok hopefully this will get you going - it worked for me in hiding a list. My source HTML looks like this:
<table>
<tbody>
...
<tr>
<td>
Hide
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</td>
</tr>
...
</tbody>
</table>
<script type="text/javascript">
function toggleListVisibility(src) {
var childrenList = src.nextSibling.nextSibling;
childrenList.style.display = "none";
}
</script>
Note I had to use two "nextSibling"'s due to a text node that is created right after the "hide" anchor. Depending on how you structure your HTML, that bit will be different.
I found the painfully simple answer that makes me feel like a doofus. All I needed to do is wrap my Repeater in a <div> element, then show/hide the entire thing.
<a href="javascript:ToggleListVisibility('<%# Container.FindControl("divWrapper").ClientID %>')" >Show/Hide</a>
<div id="divWrapper" runat="server">
<asp:Repeater ID="ChildList" runat="server">
</asp:Repeater>
</div>
function ToggleListVisibility(id) {
var wrapper = document.getElementById(id);
if (wrapper.style.display == "none") {
wrapper.style.display = "block";
} else {
wrapper.style.display = "none";
}
}
Hooray for overthinking!

Disable table row on checkbox changed event

I'd like to disable all elements within a <tr> element when a checkbox inside it is checked. My code is as follows:
<tr>
<td style="width:25px" id="td_CheckBoxClickable">
<asp:CheckBox runat="server" ClientIDMode="Static" ID="CheckBox_EnableRow" OnCheckedChanged="CheckBox_EnableRow_CheckedChanged" />
</td>
<td>
<asp:TextBox runat="server" ID="textBox_Count" />
</td>
<td>
<asp:TextBox runat="server" ID="textBox_Value" />
</td>
</tr>
and currently the CheckBox_EnableRow_CheckedChanged event is empty.
I was thinking it would be possible to look at the parent of the parent of the checkbox like this:
protected void CheckBox_EnableRow_CheckedChanged(object sender, EventArgs e) {
TableRow row = (TableRow)((CheckBox)sender).Parent.Parent;
row.Enabled = false;
}
but that doesn't seem to work.
I would recommend using jquery. Using jquery you can find the parent tr element of the checkbox, then you change the attribute of all input elements inside the tr element to disabled=true. First you have to give tr a class, say class="trclass", then you have to get the parent tr for the checkbox.
html part:
<input id="Checkbox1" type="checkbox" onchange="DsiableRow(this)" />
javascript part:
function DsiableRow(MyCHeckbox)
{
var trElement = $(MyCHeckbox).parents(".trclass");
$("trElement :input").attr("disabled", true);
}
I would solve it like this:
<input id="theCheckBox" type="checkbox" onchange="DisableRow(this)" />
function DisableRow(checkBox)
{
var $trElement= $(checkBox).closest("tr");
$trElement.find("input").attr("disabled", "disabled");
}
Differences Between HTML and XHTML
In XHTML, attribute minimization is forbidden, and the disabled attribute must be defined as .
Source: http://www.w3schools.com/tags/att_input_disabled.asp
Also note, if you use the default submitting method in the browser then:
Tip: Disabled elements in a form will not be submitted.
Source: http://www.w3schools.com/tags/att_input_disabled.asp
Use javascript to get the <tr> and make it as display:none

How can I make JavaScript run in WebBrowser control?

In my winforms aplication I have a WebBrowser control named webBrowser1.
In code all I added is navigating to a page:
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://localhost:6489/Default.aspx");
}
The code for the page to which I navigate is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TableRowShow.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
window.onload = function()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
function attach()
{
document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
}
var i = 1; // position of next tr to be shown
function addDest()
{
var trs = document.getElementById('travelTable').getElementsByTagName('tr');
if (trs[i] != null)
trs[i++].style.display = "";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="travelTable">
<tr>
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
<tr style="display: none">
<td>
<asp:TextBox runat="server" />
</td>
</tr>
</table>
<asp:HyperLink runat="server" ID="addDestination"
ClientIDMode="Static" NavigateUrl="javascript:;" >
Add Destination
</asp:HyperLink>
</form>
</body>
</html>
Seen in a browser like IE or Chrome the page looks like this:
Clicking on Add Destination anchor creates a new input:
The problem that I'm having with WebBrowser control is that it loads the page but the JavaScript doesn't work.
If I click on Add Destination nothing happens, even though the same page works well in Chrome or IE.
Placing a breakpoint and using:
webBrowser1.Document.InvokeScript("addDestination");
inside the Immediate window and then continuing to run the program activates the JavaScript in that function adding a new input.
Thanks for replies!
Try attaching the click handlers like this instead of using setAttribute in the onload and attach functions:
document.getElementById('addDestination').onclick = addDest;
You could try setting the ScriptErrorsSuppressed property to false to see whether any JavaScript errors occur.

Categories

Resources