Disable table row on checkbox changed event - c#

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

Related

Sending data from a button inside a repeater control to code-behind

I've got a button inside a repeater control, and I need to send some identifying information from the button to the onClick event so I know which ID has been clicked. My asp.net code (in part) looks like this:
<asp:Repeater ID="ParentRepeater" runat="server" OnItemDataBound="ParentRepeater_ItemDataBound">
<ItemTemplate>
<div class="bevelBox"><h3><b><%#Eval("AlbumName") %> Photo Gallery</b></h3></div>
<asp:Repeater ID="PhotoRepeater" runat="server" onitemcommand="PhotoRepeater_ItemCommand" OnItemDataBound="PhotoRepeater_DataBinding">
<HeaderTemplate>
<div class="bevelBox">
<Table>
<tr>
<td style="width:160px"><h3>Concert Photo</h3></td>
<td style="width:535px"></td>
<td><asp:Button ID="btnAddPhoto" runat="server" OnClick="btnAddPhoto_Click" Text="Add Yours" CommandArgument='<%#Eval("AlbumID") %>' UseSubmitBehavior="false" /></td>
</tr>
</Table>
</div>
Someone told me I could use the CommandArgument command to get this data to the code-behind.
On the C# side, I have this:
protected void btnAddPhoto_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string ggg = btn.CommandArgument.ToString();
mdlAddPhoto.Enabled = true;
mdlAddPhoto.Show();
}
I put a break point on the "string gggg" line, just to see what is being passed back. There's nothing indicating the <%#Eval("AlbumID") %> is being passed back.
Can anyone tell me how I can get this ID data passed back to the C# side?

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

One checkBox to be checked

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>

How can I add a custom property to a RadioButtonList items?

How can I add a bound Html5 data- attribute to the items generated with a bound RadioButtonList?
My code looks like this:
<asp:Repeater Id="QuestionList" ...>
<ItemTemplate>
<asp:RadioButtonList DataSource='<%# Eval("Answers") %>'
SelectedValue='<%# Eval("SelectedAnswerId") %>'
DataTextField="Answer"
DataValueField="AnswerId"
Tag='<%# Eval("QuestionId") %>' />
</ItemTemplate>
</asp:Repeater>
var List<Question> questions = GetQuestions();
QuestionList.DataSource = questions;
QuestionList.DataBind();
It is bound to a class structure that looks like this:
public class Question
{
int QuestionId;
string Question;
List<Answer> Answers;
}
public class Answers
{
int AnswerId;
string Answer;
bool SomeFlag;
}
I need to add SomeFlag to the UI for jQuery to use, so the end result is that each item generated should look like this:
<input type="radio" data-flag="true" ... />
Is there a way to add a html data- attribute to the input objects generated from a bound RadioButtonList?
You can use ListItem attributes to add custom attributes to the items in the radio button list. You can check how your html is generated for radio button list and make jquery to get the required data attribute for you.
On server side
ListItem li1 = new ListItem();
ListItem li2 = new ListItem();
li1.Attributes.Add("data-flag", "true");
li2.Attributes.Add("data-flag", "true");
RadioButtonList1.Items.Add(li1);
RadioButtonList1.Items.Add(li2);
Generated html for radio button list
<table id="RadioButtonList1" border="0">
<tr>
<td><span data-flag="true"><input id="RadioButtonList1_0" type="radio" name="RadioButtonList1" value="" /></span></td>
</tr><tr>
<td><span data-flag="true"><input id="RadioButtonList1_1" type="radio" name="RadioButtonList1" value="" /></span></td>
</tr>
</table>
Accessing in jquery
$(':radio[id*=RadioButtonList1]').click(function(){
alert($(this).closest('span').data('flag'));
})
You can set an Attribute in the ItemDataBound event of Repeater, try something like:
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// if it is an item (not header or footer)
if (e.Item.ItemType == ListItemType.Item)
{
// get your radioButtonList
RadioButtonList optionsList = (RadioButtonList)e.Item.FindControl("rblOptionsList");
// loop in options of the RadioButtonList
foreach (ListItem option in optionsList.Items)
{
// add a custom attribute
option.Attributes["data-flag"] = "true";
}
}
}
And remember to set the IDs and Events for your controls
<asp:Repeater Id="QuestionList" ItemDataBound="QuestionList_ItemDataBound" ...>
<ItemTemplate>
<asp:RadioButtonList ID="rblOptionsList" DataSource='<%# Eval("Answers") %>'
SelectedValue='<%# Eval("SelectedAnswerId") %>'
DataTextField="Answer"
DataValueField="AnswerId"
Tag='<%# Eval("QuestionId") %>' />
</ItemTemplate>
</asp:Repeater>
Your best bet if you need to generate the attributes server-side would be to subclass the RadioButtonList control and override the Render method.
If you have a copy of Reflector or a similar product that can show decompiled code, this would be very helpful in determining exactly where the ListItem element is being rendered as a radio button.

Categories

Resources