problem with check box in asp .net c#? - c#

The controls on aspx page are like this
Submitted
Submission Date
I want, if the check box is checked, then the textbox will be enabled I wrote
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
in the page load event. But when the page is loaded this checkbox having no effect on. Whats going wrong?

If you want the action of clicking the checkbox to enable the textbox, you'll need to do a postback when the box is checked by setting AutoPostBack="True":
<asp:CheckBox runat="server" ID="chkSubmitted" AutoPostBack="True" />
Or, you could use JavaScript:
<asp:CheckBox runat="server" ID="chkSubmitted" onclick="setSubmissionDateEnabled()" />
function setSubmissionDateEnabled()
{
var chkSubmitted = document.getElementById("<%= chkSubmitted.ClientID %>");
var txtSubmissionDate = document.getElementById("<%= txtSubmissionDate.ClientID %>");
txtSubmissionDate.disabled = !chkSubmitted.checked;
}

First set autopostback property to true of checkbox
write following code in checkbox_Selectedindexchanged event
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
else
{
txtSubmissionDate.Enabled = false;
}

Thats most likely because the default state of txtSubmissionDate is enabled already.
Try this in your page_load:
txtSubmissionDate.enabled = !chkSubmitted.Checked
To clarify, the textbox should not (!) be enabled when the Checkbox is.

Put this in Page_PreRender event. At this stage it will capture the user affected state of chkSubmitted.

Related

Having to click button twice to trigger postback in asp.net

I have some validation code in my searchbutton click event and have been having problems with it having to be clicked twice to work.
Asp Code:
<asp:Button ID="SearchButton" runat="server" Text="Search" Width="148px" OnClick="SearchButton_Click" style="height: 35px" />
Code Behind
protected void SearchButton_Click(object sender, EventArgs e)
{
string title = TitleSearch.Text;
Regex rgx = new Regex("^[0-9A-Za-z ]+$");
if (title != "" && !rgx.IsMatch(title))
{
ErrorLabel.Text = "Special characters are not allowed";
}
else
{
SearchButton.PostBackUrl = "results.aspx";
}
}
does the textbox have postback ? becaus if you change the text in the textbox it will do postback when you leave the textbox.so if you click the button the postback of the textbox fires.
I would check the textbox with java
Add in you page load event "Change EditGroup to the TextBoxName you want to check"
EditGroup.Attributes.Add("onchange", "return SomeTextChanged();");
This will add an onchange event to the textbox and it will call the java function in your aspx page when you click the button
Then in your aspx page you add "Again change EditGroup to the name of the TextBox you want to check"
<script type="text/javascript">
function SomeTextChanged() {
var Entered = document.getElementById('<%= EditGroup.ClientID %>');
if (Entered.value != "" && !Entered.value.match("^[0-9A-Za-z ]+$"))
{
alert("Special characters are not allowed");
document.getElementById('<%= EditGroup.ClientID %>').value = '';
}
else
{
}
}
</script>
So if you enter something that is not allowed you will get a message saying "Special characters are not allowed"
This will also stop you page from executing the rest of the code in the button click event.
And you also need to empty the textbox"i know this is maybe not the best way but if you don't empty the textbox and the user will click the button again it will not run the java code because the text didn't change"
So if if the text is good the java script will do nothing and the button click event will fire

How to select just a radiobutton in a repeater with postback

As I found on Internet that there is a bug from MS when we add a RadioButton inside repeater for selecting just one.
But I found this code here that solved my problem. (only one radiobutton selection in repeater)
$(function () {
$('[name$="$YourGroupName"]').attr("name", $('[name$="$YourGroupName"]').attr("name"));
$('[name$="$YourGroupName"]').click(function () {
//set name for all to name of clicked
$('[name$="$YourGroupName"]').attr("name", $(this).attr("name"));
});
});
But it only works when the radiobutton is not set to autopostback. But I need to do a postback when I select a radiobutton and a response to the database. But.... anytime that I do a click on a radiobutton with postback, always the first in the list is selected and the ItemDataBound it's not working because of the jquery function which it's renaming all the radiobuttons with the same name.
Suggestions?
Try to add this script instead of the one you're using at the end of the page after the repeater :
<script>
var radios = $("input:radio");
radios.click(function () {
radios.removeAttr('checked');
$(this).prop("checked", true);
//$(this).attr('checked', 'checked'); // jQuery < 1.6
return true;
});
</script>
This will allow the AutoPostBack of your radiobutton to work again.

Unselect radio button list on click

I need to unselect radio button in radio button list, i know it is more sensible to use checkbox but the management wants radio button to be unchecked.
RadioButtonList control is a collection of ListItems. To clear one radio button in the control you need to use Index for that particular item. To clear all radio buttons in the control, there is a method "ClearSelection()".
//To Unselect First Item
RadioButtonList1.Items[0].Selected = false;
//To unselect all Items
RadioButtonList1.ClearSelection();
hope this will resolve your issue.
private void Clear()
{
if(RadioButton1.Checked)
{
RadioButton1.Checked = false;
}
}
Use this:
RadioButton1.Checked = false;
myRadioButtonList.SelectedIndex = -1;
Hope this help.
You mean you want it to be possible for your radio button group to have zero values selected? Technically, you can just ensure that no radio in the group has its checked value set. checked="" or just delete the entire attribute.
Be aware that this is an invalid state for the radio group. It's like a boolean that is set to neither true nor false. It makes no sense semantically and is in violation of the HTML spec.
If you are constrained to a radio group, the only valid option is to include one radio that represents a 'none of the other options' state.
I had the same problem. In my case, I was using the radio button checkedChanged event to automatically append a medical documentation string snippet into a rich text box control. The snippet would be different for each radio button selected, and the requirement was that only one choice could be allowed. So radio buttons were the best choice instead of check boxes. The problem was that if the user wanted to remove ALL of the text snippets from the textbox, the s/he could just manually select the text from the box and delete it -- but at least one radio button would remain selected.
So, I found that the easiest way to fix this would be to add a button to the form and use its _Click event to set the specified radio button checked status to false.
So, My code looked like this...
// for rad 1
private void rad_NoDifferent_CheckedChanged(object sender, EventArgs e) {
if(rad_NoDifferent.Checked) {
rtb_GSC_Notes.AppendText(sRating_NoDiffMsg);
} else {
rtb_GSC_Notes.Text = rtb_GSC_Notes.Text.Replace(sRating_NoDiffMsg, sNoMsg.TrimEnd());
}
}
// for rad 2
private void rad_VeryDifferent_CheckedChanged(object sender, EventArgs e) {
if(rad_VeryDifferent.Checked) {
rtb_GSC_Notes.AppendText(sRating_VeryDiffMsg);
} else {
rtb_GSC_Notes.Text = rtb_GSC_Notes.Text.Replace(sRating_VeryDiffMsg, sNoMsg.TrimEnd());
}
}
// for rad 3
private void rad_Unsure_CheckedChanged(object sender, EventArgs e) {
if(rad_Unsure.Checked) {
rtb_GSC_Notes.AppendText(sRating_UnsureMsg);
} else {
rtb_GSC_Notes.Text = rtb_GSC_Notes.Text.Replace(sRating_UnsureMsg, sNoMsg.TrimEnd());
}
}
// for button reset
private void btn_ClearRadioButtons_Click(object sender, EventArgs e) {
rad_NoDifferent.Checked = false;
rad_Unsure.Checked = false;
rad_VeryDifferent.Checked = false;
}
Recently I was facing same issue however I found the solution with Radio button.
below are the aspx code for radio button
<div>
<asp:RadioButton ID="RadioButton1" GroupName="myg" onClick="clicked(this.id);" runat="server" />
<asp:RadioButton ID="RadioButton2" GroupName="myg" onClick="clicked(this.id);" runat="server" />
<asp:RadioButton ID="RadioButton3" GroupName="myg" onClick="clicked(this.id);" runat="server" />
<asp:RadioButton ID="RadioButton4" GroupName="myg" onClick="clicked(this.id);" runat="server" />
</div>
Just write below java script.
<script type="type/javascript">
var arr = [];
function clicked(radid) {
var ra = document.getElementById(radid);
if (arr.indexOf(radid) < 0) {
arr.splice(0, arr.length);
arr.push(radid);
}
else {
arr.splice(0, arr.length);
ra.checked = false;
}
}
</script>
Hope this will solve your purpose.
WPF/C#
if (RadioBTN.IsChecked == true) {
RadioBTN.IsChecked = false;
}

ASP.Net: How to maintain TextBox State after postback

I would like to know how to maintain the control state that has been modified in Javascript.
I have two TextBoxes, one DropDownList and a button (all Runat=Server) in C# ASP.net 2010 Express.
First textbox is just accept whatever data user input. Second textbox enable state will change based on DDL selected value. If ddl selected value is "-", second textbox will become Enabled = False.
If not "-", it will become Enabled = True. This enable is done through Javascript.
In my Page Load event, I have below code.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
And in my aspx page, I have some javascript which will clear the textbox data and disable the textbox.
Here is for Second Textbox.
<asp:TextBox ID="txtKey2" runat="server" Width="425px" EnableViewState="False"></asp:TextBox>
And here is for DDL.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
Here is the code for my Javascript. (I have a plan to implement other textbox and ddl so in my code I have Else if condition).
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
I have nothing in button click event.
By using above all code, when I run the project, the page loads Ok.
The second textbox enabled state is set to False (through Page_Load event). So far Ok.
Then from my browser, I choose ddl value to other instead of "-", the textbox become enable because of javascript. This is Ok.
I input the value and click on the button. Page PostBack happens here. Textbox is still enabled (because of EnableViewState = False for my textbox).
I choose ddl value to "-", second textbox became disabled.
Click on the button, page postback happen, but this time the textbox is still enabled. << This is the issue I'm trying to solve. I change EnableViewState, ViewStateMode in different values but still the same.
Is there any solution for this one?
Here is my test image URL.
State 1 ,
State 2 ,
State 3
Sorry for the long post.
I have tried and found no solution beside using additional HiddenField control.
I update the hidden field value when I update the status of my textbox in Javascript.
And on my Page Load event, I checked all the hidden field values and based on the hiddenfield values, I will disable/enable my textboxes which is for me not a good solutions.
Imagine I have 10 or 15 textboxes on my form, I need to have 10 or 15 hidden field just to maintain client side action result.
Currently, this is the only solution for me.
I'm not sure can this consider as 'Answer' so I haven't close this question yet.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
You Have to call you javascript function on every postback.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
ScriptManager.RegisterClientScriptBlock(this, typeof(System.Web.UI.Page), "MyJSFunction", "EnableSelkey("+selKey1.SelectedValue+",1);", true);
It May be help you, Let me know for further help.
I found a solution that worked was to put the code that I put in the !IsPostBack section for enabling and disabling the textboxes also directly in the page load event.

Mutually exclusive selection of Radiobutton in gridView.ASP.NET C#

<asp:TemplateField HeaderText="Select One">
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow di in GridView1.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
if (rad.Checked&&rad!=null)
{
s = di.Cells[1].Text;
}
}
Response.Redirect("applicants.aspx?form=" +s);
}
I'm selecting the rows that are selected with this but I have a problem here I want user to be able to select only one radiobutton but its allowing all the radiobuttons to be selected at once.Can you help me in removing this problem please.
please.
Maybe I'm too late here on the party but this will do the trick,
check out here......
This might be useful for someone watching this answer in the future.
In the ASP page you need to set the GroupName property to be the same for all the radio buttons, e.g.:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="RadioGroup" />
well for that you can use follwing code
first of all you should define the groupName.The follwing code will work
<asp:RadioButton ID="RadioButton1" OnCheckedChanged="rbSelector_CheckedChanged" AutoPostBack="true" GroupName="Apply" runat="server"></asp:RadioButton>
C#
protected void rbSelector_CheckedChanged(object sender, System.EventArgs e)
{
foreach (GridViewRow oldrow in GridView2.Rows)
{
((RadioButton)oldrow.FindControl("RadioButton1")).Checked = false;
}
//Set the new selected row
RadioButton rb = (RadioButton)sender;
GridViewRow row = (GridViewRow)rb.NamingContainer;
((RadioButton)row.FindControl("RadioButton1")).Checked = true;
}
You can try this link to select single radiobutton in grid : http://www.c-sharpcorner.com/uploadfile/krishnasarala/select-single-radio-button-in-gridview-in-Asp-Net/
Using the GroupName property by itself won't work, each radio button will still get a unique name attribute since they're in different rows of the grid.
One option is to emit the radio button markup manually using a Literal control (example). This will make it easy to group the radio buttons on the client-side, but requires a bit more work to determine which button was selected on postback.
When I needed this behavior, I found it easier to keep the radio buttons as server-side controls, and just enforce the button group w/ jQuery. Put your RadioButton in a TemplateField as you've shown, then add this code to uncheck all the other buttons when one is checked:
$(document).ready(function () {
// could also pass in a unique ID selector
createManualRadioButtonGroupForGridView(".myGridViewClass");
});
function createManualRadioButtonGroupForGridView(gridViewSelector) {
$(gridViewSelector + " input[type=radio]").change(function () {
var checkedRadioButton = this;
$(gridViewSelector + " input[type=radio]").each(function (e) {
if (this !== checkedRadioButton) {
$(this).prop("checked", false);
}
});
});
}

Categories