when i try to check if a radio button is checked, the code doesnt execute - asp.net

i am trying 2 make a quiz in asp.net.
the mcq choices r displayed using radio buttons. in code behind, when i try 2 check if radiobutton is checked, d code under that if statement does not execute.
aspx code:
<ItemTemplate>
<asp:Literal ID="Literal1" runat="server" Text='<%#Eval("ques") %>'></asp:Literal><br />
<asp:RadioButton GroupName="a" ID="RadioButton1" Text='<%#Eval("ch1") %>' runat="server" /><br />
<asp:RadioButton GroupName="a" ID="RadioButton2" Text='<%#Eval("ch2") %>' runat="server" /><br />
<asp:RadioButton GroupName="a" ID="RadioButton3" Text='<%#Eval("ch3") %>' runat="server" /><br />
<asp:RadioButton GroupName="a" ID="RadioButton4" Text='<%#Eval("ch4") %>' runat="server" /><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("ans") %>' Visible="false"></asp:Label><br />
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label><br />
</ItemTemplate>
code behind:
protected void Button1_Click(object sender, EventArgs e)
{
int count = 0;
foreach(RepeaterItem Items in Repeater1.Items)
{
RadioButton r1 = (RadioButton)Items.FindControl("RadioButton1");
RadioButton r2 = (RadioButton)Items.FindControl("RadioButton2");
RadioButton r3 = (RadioButton)Items.FindControl("RadioButton3");
RadioButton r4 = (RadioButton)Items.FindControl("RadioButton4");
Label l3 = (Label)Items.FindControl("Label3");
Label l=(Label)Items.FindControl("Label1");
l3.Text = "hello?";
if (r1.Checked)
{
if(r1.Text==l.Text)
count++;
}
else
{
if (r2.Checked)
{
if(r2.Text==l.Text)
count++;
}
}
// and so on for all 4 options
}
Label2.Visible = true;
Label2.Text = "your score is " + count; //always zero!
}

If you're stepping through the debugger, and your line
if(r1.Text==l.Text)
count++;
isn't executing, then I would guess that the line if (r1.Checked) is evaluating to false.
On your Page_Load() method for this page, are there any databindings or manipulation of these radio buttons? If so, unless you wrap them in a if(!Page.IsPostBack){ ... } conditional then it will wipe out whatever the user did to the radio button, hence r1.Checked would be false.
I hope that might help :) Good luck.

You'll need to do the following:
Set the AutoPostBack on the radio button control to true.
Set the OnItemCommand on the repeater control to "Button1_Click"
Change the signature of the Button1_Click method to protected void Button1_Click(object sender, RepeaterCommandEventArgs e)
That will at least trigger the method in your code behind.

Related

programmatically added click event in user control won't fire

I'm having issues getting the click event for a button contained within a programmatically added user control to fire. I understand that the event must be wired up each time a new user control is added, and I'm pretty sure I'm doing that, but still nothing. The click event for the button works fine for the first user control, which is not added programmatically. Here's the markup for the user control....
<asp:Panel ID="pnlAddressForm" runat="server">
<asp:Label ID="lblStreet" runat="server" Text="Street Address"></asp:Label>
<asp:TextBox ID="txtStreet" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblCity" runat="server" Text="City"></asp:Label>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblState" runat="server" Text="State"></asp:Label>
<asp:TextBox ID="txtState" runat="server"></asp:TextBox>
<br /><br />
<asp:Label ID="lblZip" runat="server" Text="Zip"></asp:Label>
<asp:TextBox ID="txtZip" runat="server"></asp:TextBox>
<br /><br />
<asp:Button ID="btnRemoveAddress" runat="server" Text="Remove Address" OnClick="btnRemoveAddress_Click" />
</asp:Panel>
...and here's the markup for the main page...
<form id="form1" runat="server">
<div>
<My:FormUserControl runat="server" ID="myFormUserControl" />
<br /><br />
<hr />
<My:AddressUserControl runat="server" ID="myAddressUserControl" />
<br /><br />
<asp:PlaceHolder ID="phAddresses" runat="server"></asp:PlaceHolder>
<br /><br />
<asp:Button ID="btnAddAddress" runat="server" Text="Add Another Address" OnClick="btnAddAddress_Click" />
</div>
<br /><br />
<hr />
<asp:Button ID="btnSubmit" runat="server" Text="Create PDF" OnClick="btnSubmit_Click" />
</form>
..as you can see it already contains one AddressUserControl declaratively. All subsequent AddressUserControls are added to phAddresses once btnAddAddress is clicked. AddressUserControls are added this way in the code behind...
private static List<AddressUserControl> addresses = new List<AddressUserControl>();
protected void Page_PreInit(object sender, EventArgs e)
{
int addressCount = 0;
foreach (AddressUserControl aCntrl in addresses)
{
Literal ltlSpace = new Literal();
ltlSpace.Text = "<br /><br />";
phAddresses.Controls.Add(aCntrl);
phAddresses.Controls.Add(ltlSpace);
addressCount++;
}
}
When btnAddAddress is click this event handler runs...
protected void btnAddAddress_Click(object sender, EventArgs e)
{
AddressUserControl aCntrl = LoadControl("~/UserControls/AddressUserControl.ascx") as AddressUserControl;
findAddressControlRemoveButton(aCntrl);
addressUserControlButton.ID = "btnRemoveAddress" + addresses.Count + 1;
addressUserControlButton.Click += new EventHandler(addressUserControlButton_Click);
addresses.Add(aCntrl);
}
...and here's the addressUserControlButton event handler. This never runs, I suppose I'm not adding it correctly in the above handler?
private void addressUserControlButton_Click(object sender, EventArgs e)
{
Button thisButton = sender as Button;
thisButton.Text = "Why Hello";
}
EDIT - Ok, so I moved the eventhandler assignment to Page_PreInit instead of within btnAddAddress_Click, like so....
protected void Page_PreInit(object sender, EventArgs e)
{
int addressCount = 0;
foreach (AddressUserControl aCntrl in addresses)
{
Literal ltlSpace = new Literal();
ltlSpace.Text = "<br /><br />";
phAddresses.Controls.Add(aCntrl);
findAddressControlRemoveButton(aCntrl);
addressUserControlButton.ID = "btnRemoveAddress" + addressCount;
addressUserControlButton.Click += new EventHandler(addressUserControlButton_Click);
phAddresses.Controls.Add(ltlSpace);
addressCount++;
}
}
Not totally clear on why or how this fixed the problem though.
When you add any control programmatically, you need to register click event after that.

ASP.NET Textbox AutoPostBack Not Firing

After searching I've found a number of suggestions, but none of them are fixing the issue.
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text=""></asp:TextBox>
In the properties window, EnableViewState = True for the TextBox (Suggested here). I am typing a new value into the TextBox and then hitting the Tab key. Nothing happens nor does the break point at if(IsPostBack...) break.
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && uid.Text != "" && pw.Text == "")
{
Do stuff
}
}
UPDATE: Other TextBox setups I've tried:
<asp:TextBox runat="server" ID="uid" Text="" AutoPostBack="True" OnTextChanged="UidTextChanged"></asp:TextBox>
protected void UidTextChanged(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('it works');", true);
}
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');" OnTextChanged="UidTextChanged"></asp:TextBox>
And
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" onblur="__doPostBack('','');"></asp:TextBox>
Whenever AutoPostBack is set to true, I receive the following error in the browser console:
"Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function
__doPostBack
(anonymous function)"
When I have the onblur property set, I receive the exact same error except instead of anonymous function it says onblur.
You could add a javascript event to the onblur for it. onblur='__doPostBack('','');'
That would cause your text box to cause a postback once it is tabbed out of.
Edit: It should be " not ' <asp:TextBox ID="TextBox1" runat="server" onblur="__doPostBack('','');" /> Just tried that and it works. Try removing the AutoPostBack="True"
Edit 2: Base on your pastebin....
<asp:Button runat="server" UseSubmitBehavior="True" ID="submit" Text="Save"
onclick="SubmitClick"/>
You can't have an ID of "submit". Change that to "btnSubmit" and the Javascript solution will work and I bet the Auopostback solution will too.
http://www.xpertdeveloper.com/2012/05/property-submit-of-object-is-not-a-function/ will explain the problem.
You can add OnTextChanged="TextBox1_TextChanged" on your textBox
Nota : It's important to set event fire, no just AutoPostBack="true".
<asp:TextBox runat="server" ID="uid" AutoPostBack="True" Text="" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
Code Behind:
protected void TextBox1_TextChanged(object sender, System.EventArgs e) {
.....
}

how to disable server side validation on asp.net web forms from browser?

I wanted to disable asp.net validation server controls from browser. I checked online but did not find any way to disable the server side validation; it can be disabled only on the client side using JS/jQuery.
Here is the scenario: I have a checkbox and selecting which displays a set of text boxes. Only if the checkbox is checked, required field validator should fire for the text boxes. I don't want to call a postback on checkbox. Actually those chceck boxes will be generated with jQuery templating so postback is not an option to enable disable validtion.
I would like to know whether there is any way we can enable disable the .CausesValidation property for the controls from browser using some setting? Or is there a way to capture the controls which are to be considered for validation slectively in some event before page_load?
[Update]
Based on Accepted answer, here is my solution:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req1" ControlToValidate="textbox1" runat="server"
ErrorMessage="enter text"></asp:RequiredFieldValidator>
<asp:TextBox ID="textbox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="req2" ControlToValidate="textbox2" runat="server"
ErrorMessage="enter text for 2"></asp:RequiredFieldValidator>
<asp:CheckBox ID="check1" runat="server" Text="choose" />
<asp:Button ID="submitBtn" runat="server" OnClick="submitBtn_Click" Text="submit" />
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:ValidationSummary ID="summary" runat="server" />
</div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
req1.Enabled = false;
req2.Enabled = false;
}
protected void submitBtn_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
Response.Write("valid form");
}
else
{
Response.Write("invalid form");
}
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (check1.Checked)
{
req1.Enabled = true;
req1.Validate();
}
}
The solution for me would be to use a CustomValidator with a OnServerValidate method.
In the OnServerValidate method I would check if the checkbox is checked, in that case I would verify if the textboxes are filled. It is not necessary to do any change in the CausesValidation property.
The only condition is not to include the property "ControlToValidate". A CustomValidator does not fire if the textbox is empty that's why.
So the code would be like this:
<asp:ValidationSummary ID="vs" runat="server" ValidationGroup="prueba" />
<asp:CheckBox ID="chb" runat="server" Text="Check" />
<asp:TextBox ID="txbBox" runat="server"></asp:TextBox>
<asp:CustomValidator ID="cvBox" runat="server" ErrorMessage="Error" ValidationGroup="prueba"
OnServerValidate="Validarcaja"></asp:CustomValidator>
<asp:Button ID="btn" runat="server" Text="Prueba" />
And the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Page.Validate();
}
}
protected void Validarcaja(object source, ServerValidateEventArgs args)
{
if (chb.Checked)
{
if (txbBox.Text == String.Empty)
{
cvBox.IsValid = false;
}
}
}

how do i get access to the label inside gridview/repeater

as you can see in my code... i have a label inside ItemTemplate and what i want is when i click on that particular control i would like to access to the label so that i can update the status...
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1" OnItemCreated="Repeater1_ItemCreated" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
Book:
<asp:Label ID="lblStatus" runat="server"></asp:Label>
<Mycontrol:Content1 ID="EmpControl" runat="server" OnMyControlClick="EmpControl_clicking" />
<br />
</ItemTemplate>
</asp:Repeater>
protected void EmpControl_clicking(object sender, EmployeeEventArgs e)
{
// how do i get access to the lblStatus???
}
You will need to use the FindControl method to access controls within templates:
protected void EmpControl_clicking(object sender, EmployeeEventArgs e)
{
MyControl myControl = (MyControl)sender;
Label c = (Label)myControl.Parent.FindControl("lblStatus");
}

Required field validater in repeater

I have a repeater control and textbox in that repeater. I want a required field validator in the textbox ho can i do this
<asp:Repeater id="myRep" OnItemDataBound="rep_ItemDataBound" runat="server">
<ItemTemplate>
<asp:TextBox id="tx" runat="server" />
<asp:RequiredFieldValidator id="myVal" ControlToValidate="tx" ErrorMessage="Required" runat="server" />
</ItemTemplate>
</asp:Repeater>
UPDATE
Add this to code-behind (also modify the markup a bit to subscribe to an event, see above):
protected void rep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RequiredFieldValidator val = (RequiredFieldValidator)e.Item.FindControl("myVal");
TextBox tb = (TextBox)e.Item.FindControl("tx");
val.ControlToValidate = tb.ID;
}
If you want all textboxes in a repeater to be validated by a single button click then thats simple like this
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:TextBox ID="txt" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator ID="rqf" ControlToValidate="txt"
ErrorMessage="*" ValidationGroup = "TestValidationGroup" runat = "server">
</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID = "btnSubmit" runat = "server" ValidationGroup = "TestValidationGroup" />
No need to check for any event for databound or anything.
You can set ControlToValidate value on repeater itemdatabound.
Try this one
<asp:Repeater ID="rptSample" runat="server">
<ItemTemplate>
Name:<br />
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" ControlToValidate="txtName" runat="server" Display="Static" ErrorMessage="Name field cannot be left blank"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
protected void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
((RequiredFieldValidator)e.Item.FindControl("myVal")).ValidationGroup = ((TextBox)e.Item.FindControl("tx")).UniqueID;
}
}
protected void Repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e) {
tblData tbldata = e.Item.DataItem as tblData;
RequiredFieldValidator val = (RequiredFieldValidator)e.Item.FindControl("rfv");
if (tbldata.FieldName.ToUpper().Contains("NOT NULL")) {
TextBox tb = (TextBox)e.Item.FindControl("txtDATFieldName");
val.ControlToValidate = tb.ID;
}
else {
val.Enabled = false; // disable when you dont need a validator
}
}
Maybe you want have a validation per row... Set the validation group to a group per row like this
ValidationGroup='<%# "gropname" + Eval("Id") %>'
do this in the validator, textbox and the button
HTH
G.
I kept getting a duplicate key exception in RegisterExpandoAttribute trying to do this.
I was using a UserControl inside a repeater, when "OnDataBinding" instead of "ItemDataBinding"
This worked for me:
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.DataBinding" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
foreach (Control ct in this.Controls)
{
BaseValidator bv = ct as BaseValidator;
if (null == bv)
{
continue;
}
bv.ControlToValidate = this.FindControl(bv.ControlToValidate).ID;
bv.ValidationGroup = this.ValidationGroup;
}
}
And yes, I don't think it makes any sense either

Resources