How to enable button after filling text box using c# - c#

As per AntLaC link suggestion I have tried but it is not working in my coding. please help me where i made mistake please let me know. Below is back end code
protected void txtCardHolderName1_TextChanged(object sender, EventArgs e)
{
if (txtCardHolderName1.Text.Length > 0)
{
btnNext.Enabled = true;
}
else
{
btnNext.Enabled = false;
}
}
aspx code
<asp:UpdatePanel ID="upServiceFee" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtCardHolderName1" runat="server" CssClass="txtbox" Width="220px" ValidationGroup="ServiceFee" MaxLength="100" AutoPostBack="true" AutoCompleteType="Disabled" autocomplete="off" OnTextChanged="txtCardHolderName1_TextChanged"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnNext" runat="server" CssClass="btn btnBlue btnStep" Text="Submit" OnClick="btnSubmit_Click" CausesValidation="true" ValidationGroup="ServiceFee" Enabled="false" />

You can handle TextChanged event even when you don’t use the AutoPostBack property.

you could try to change the if statement to:
if(textBox != null)

I got My answer with the help of javascript,Thank you so much for helping me. Just i put below code in postback
string var = ClientScript.GetPostBackEventReference(btnNext, "").ToString();
btnNext.Attributes.Add("onClick", "javascript :if ( Page_ClientValidate() ){this.disabled=true; this.value='Please Wait...';" + var + "};");

Related

Update Panel, confirm button and update progress don't seem to work together

At the moment I have no luck trying to get the three of them to work together and i have had only luck with the updatepanel and update progress nothing the confirm button so far.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnEnter" runat="server" Text="Update" Width="180" Style="margin-left:157px;"
OnClick="btnEnter_Click"
CssClass="button-success pure-button"/>
<asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" runat="server"
TargetControlID="btnEnter"
ConfirmText="Do you want to see submit?"
ConfirmOnFormSubmit="false">
</asp:ConfirmButtonExtender>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<div class="overlay"></div>
<div class="modal">
<h2>Please Wait.....</h2>
<img alt="Loading..." src="/Images/loading.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
I have used the javascript function confirm before this and have taken it out
it was just a onclientclick on the button.
OnClientClick="return confirm('Are you sure you want to submit?');"
but I need to check validation of the page first before asking to submit but I am clueless about it.
here's the behind code atm for the button.
protected void btnEnter_Click(object sender, EventArgs e)
{
if(Page.IsValid )
{
}
}
You could do this even easier and more efficient using client side like this:
you just need to add onclientclick attribute in your <asp:Button ID="btnEnter" control and remove the <asp:ConfirmButtonExtender ID="ConfirmButtonExtender1" from your code.
it would be look like this then :
<asp:Button ID="btnEnter" runat="server" Text="Update"
Width="180" Style="margin-left:157px;"
OnClick="btnEnter_Click"
CssClass="button-success pure-button"
OnClientClick="return confirm('Do you want to see submit?');"/>
and that's it!
So you DO NOT need asp:ConfirmButtonExtender anymore.
UPDATE 1
If you require to check the condition first on the code behind then you could use the code below:
protected void btnEnter_Click(object sender, EventArgs e)
{
if(Page.IsValid )
{
ScriptManager.RegisterStartupScrip(UpdatePanel1, this.GetType(),
"confirm", "return confirm('Are you sure you want to submit?');", true);
}
}
try to Validate your form using jquery then throw the confirmation dialog if the valiation succeeded .
function ValidateForm(){
//validation
if(succeeded){
return confirm('are you sure?');
}else{
return false
}
}
$(document).ready(function(){
$('#' + '<%= btnEnter.ClientID %>').click(function(){
return ValidateForm();
});
});

Viewstate not preserved when handling exception

I'm using a detailsview for a dialog to the user, and it seems that the viewstate is not preserved when there is an error inserting the data.
I'm using a OnInserted handler on the datasource to check if there was an exception like so:
protected void areaInsertHandler(Object sender, SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
// There was an error in submitting, show the error dialog
ScriptManager.RegisterClientScriptBlock(Page, GetType(), "DialogHandler", "showError('#overlayAreas');", true);
e.ExceptionHandled = true;
}
}
Which simply calls the client side JS function:
function showError(overlayName) {
$(".msgError").css('visibility', 'visible');
$(overlayName).css('visibility', 'visible');
}
My detailsview looks something like this:
<asp:UpdatePanel ID="AreaUP" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="overlayAreas" class="overlay">
<asp:DetailsView
ID="DetailsView_Areas"
runat="server"
Visible="True"
AutoGenerateInsertButton="False"
AutoGenerateRows="False"
caption="<a style='font-weight: bold;'>Bold</a> = Required field"
CaptionAlign="Bottom"
headertext="Create new area"
EnableViewState="true"
DataKeyNames="Area_Name"
DataSourceID="AreasSource"
DefaultMode="Insert">
<Fields>
...
</Fields>
</asp:DetailsView>
</div>
<br />
<asp:Button width="200" height="30" ID="Button_CreateArea" runat="server" OnClientClick="return btnToggle('#overlayAreas')" Text="Create new area" />
</ContentTemplate>
</asp:UpdatePanel>
It all works fine, but for some reason the ASP viewstate is not preserved. Meaning that if I fill out incorrect information in the form and submit I will get the appropriate error and the dialog will still be displayed. But the fields are not filled out with my old values.
If someone could give me some pointers or help me out I'd greatly appreciate it
EDIT 10-08: Still haven't been able to solve it, any ideas at all?
basically:
avoid DetailsView_Areas.DataBind()
if (DetailsView_Areas.CurrentMode != DetailsViewMode.Insert) DetailsView_Areas.DataBind();
create the ItemInserted event for your DetailsView_Areas and put
if (e.AffectedRows < 0) e.KeepInInsertMode = true;
see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.detailsviewinsertedeventargs.affectedrows(v=vs.110).aspx

asp.net c# validation

I am trying to create a simple form that uses radio buttons. I set the radio button to AutoPostBack = True, this way if the radio button is true/false, a subpanel is Shown or Hidden. The radio buttons are required fields. I also have a hidden textbox that the value of the selected radio button is inserted and this textbox is what I validate against (empty or not).
Problem 1:
This works until you go to submit and the validation fails. The validation messages show, then when you click on one of the radio buttons with AutoPostBack = True, all the validation disappear. I can resolve this by adding Page.Validate() to the method that runs when the radio button is clicked. But, I do not want the Page.Validate() to run unless the page was already showing validation errors (so it will not re-validate unless the form was already submitted and failed the validation).
As it stands, before the form is submitted and fails validation: when you click on any radio button question, all the other questions requiring validation show the validation error. I am only looking to overcome the AutoPostBack which is clearing all the validation messages that are shown when you had click submit.
Problem 2:
I would like to be able to change the color of the question if it does not pass validation. I added the javascript to override the default .net settings. I got this to work, but only when you click the submit button and not after a RadioButton AutoPostBack.
Currently, When you click submit all the required questions turn red and also display the required validation message. But if you click a radio button to start fixing the validation errors, on the AutoPostBack, the all the questions that were now red in color changes back to the orignal black and the required validation message is still shown. How can I call the Javascript to run again along with the Page.Validation() in the code behind method?
Any help would be greatly appricated! Thanks
Below is an example of the code so far.
ASPX Code:
<asp:Table ID="Table1" runat="server" CellSpacing="0" CellPadding="0">
<asp:TableRow>
<asp:TableCell CssClass="question">
<label>4. Have you had an abnormal result from a prenatal test (e.g. amniocentesis, blood test, ultrasound)?</label>
</asp:TableCell>
<asp:TableCell CssClass="answer">
<ul class="selectGroup">
<li>
<asp:RadioButton ID="Q4_true" runat="server" Checked='<%# Bind("Q4_yes") %>' Text="Yes"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" /></li>
<li>
<asp:RadioButton ID="Q4_false" runat="server" Checked='<%# Bind("Q4_no") %>' Text="No"
GroupName="4" OnCheckedChanged='RB_QuestionSubPane_YN' AutoPostBack="true" />
</li>
<asp:TextBox ID="Q4_validationBox" runat="server" CssClass="hiddenField" Enabled="false"
Text=''></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" EnableViewState="true" ControlToValidate="Q4_validationBox"
Display="Dynamic" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ul>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
Code Behind
protected void RB_QuestionSubPane_YN(object sender, EventArgs e)
{
RadioButton radio_Selected = (RadioButton)sender;
string radio_QuestionID = Convert.ToString(radio_Selected.ID);
(((TextBox)FormView1.FindControl(strQuestionID + "_validationBox")).Text) = radio_Selected.ID.ToString();
Page.Validate();
}
JavaScript
ValidatorUpdateDisplay = function (val) {
var ctl = $('#' + val.controltovalidate);
var eCount = 0;
for (var i = 0; i < Page_Validators.length; i++) {
var v = Page_Validators[i];
if (v.controltovalidate == val.controltovalidate) {
if (!v.isvalid) {
eCount++;
ctl.addClass('validationError');
$('td.question:eq(' + i + ')').addClass('red');
}
};
}
if (eCount > 0) {
ctl.addClass('validationError');
} else {
ctl.removeClass('validationError');
$('td.question:eq(' + i + ')').removeClass('red');
}
if (typeof (val.display) == "string") {
if (val.display == "None") {
return;
}
if (val.display == "Dynamic") {
val.style.display = val.isvalid ? "none" : "inline";
return;
}
}
if ((navigator.userAgent.indexOf("Mac") > -1) &&
(navigator.userAgent.indexOf("MSIE") > -1)) {
val.style.display = "inline";
}
val.style.visibility = val.isvalid ? "hidden" : "visible";
}
It sounds like what you really need is custom validation. That way you can fully customize your validation to meet your needs.
Here is a simple example:
<script language="javascript" type="text/javascript" >
function CustomValidator1_ClientValidate(source,args)
{
//put your javascript logic here
}
//-->
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="direction" Text="left" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="direction" Text="right" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic" ErrorMessage="please choose" ClientValidationFunction="CustomValidator1_ClientValidate" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
</div>
</form>
</body>
Server Side
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = RadioButton1.Checked || RadioButton2.Checked;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//validate is successful.
}
}

Validation with one radio button option only

I have a radiobuttonlist with three choices. When a user clicks on the "Provided" option, two textboxes open underneath it. These two are required when selecting that option. How can I require these two only when that option is marked but not if it isn't and still allow me to process the form? I tried using ValidationGroup, but since I am still new to developing, I think I am missing something. Any guidance would be appreciated, thanks in advance!
<asp:RadioButtonList ID="rblCreat" runat="server" RepeatDirection="Horizontal" CssClass="rblMargin rblCreat">
<asp:ListItem>N/A</asp:ListItem>
<asp:ListItem>DIC to Obtain</asp:ListItem>
<asp:ListItem>Provided</asp:ListItem>
</asp:RadioButtonList>
<div style="display: none;" id="provided-fields">
<br />
<p style="margin-left: 250px">
Results:
<asp:TextBox ID="txtCreatResults" runat="server" Width="99px" TabIndex="21" Height="22px"
CssClass="margin"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvResults" runat="server" ControlToValidate="txtCreatResults"
ErrorMessage="*Required" ValidationGroup="provided"></asp:RequiredFieldValidator>
<br />
Date:
<asp:TextBox ID="txtCreatDate" runat="server" Width="99px" TabIndex="22" onkeydown="return DateFormat(this, event.keyCode)"
Height="22px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvDate" runat="server" ControlToValidate="txtCreatDate"
ErrorMessage="*Required" ValidationGroup="provided"></asp:RequiredFieldValidator>
</p>
</div>
Your code Behind
protected void Page_Load(object sender, EventArgs e)
{
rblCreat.Items[0].Attributes.Add("onclick", "abc('1');");
rblCreat.Items[1].Attributes.Add("onclick", "abc('2');");
rblCreat.Items[2].Attributes.Add("onclick", "abc('3');");
}
Your Java Script
<script language="javascript" type="text/javascript">
function abc(ID) {
if (ID == '3') {
var btn = document.getElementById("<%=btn.ClientID%>");
btn.onclick = function () {
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btn.id, "", true, "provided", "", false, false));
}
document.getElementById('providedfields').style.display = 'block';
}
if (ID == '1' || ID == '2') {
var btn = document.getElementById("<%=btn.ClientID%>");
btn.onclick = function () {
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(btn.id, "", true, "newValGroup", "", false, false));
}
document.getElementById('providedfields').style.display = 'none';
}
}
</script>
Your HTML
<asp:radiobuttonlist id="rblCreat" runat="server" repeatdirection="Horizontal" cssclass="rblMargin rblCreat">
<asp:ListItem Value="1">N/A</asp:ListItem>
<asp:ListItem Value="2">DIC to Obtain</asp:ListItem>
<asp:ListItem Value="3">Provided</asp:ListItem>
</asp:radiobuttonlist>
<div style="display: none;" id="providedfields">
<br />
<p style="margin-left: 250px">
Results:
<asp:textbox id="txtCreatResults" runat="server" width="99px" tabindex="21" height="22px"
cssclass="margin"></asp:textbox>
<asp:requiredfieldvalidator id="rfvResults" runat="server" controltovalidate="txtCreatResults"
errormessage="*Required" validationgroup="provided"></asp:requiredfieldvalidator>
<br />
Date:
<asp:textbox id="txtCreatDate" runat="server" width="99px" tabindex="22" height="22px"></asp:textbox>
<asp:requiredfieldvalidator id="rfvDate" runat="server" controltovalidate="txtCreatDate"
errormessage="*Required" validationgroup="provided"></asp:requiredfieldvalidator>
</p>
</div>
<asp:button id="btn" validationgroup="provided" runat="server" />
When you click on the button it will postback in case of other then provided options.
I believe a CustomValidator could help you with this.
<asp:CustomValidator
runat="server"
id="cusCustom"
controltovalidate="txtCreatDate"
onservervalidate="cusCustom_ServerValidate"
errormessage="You must enter a text." />
and then write the method in your code behind with whatever logic you might need.
protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (rblCreat.SelectedIndex == 1)
{
if (e.Value.Length > 0)
{
e.IsValid = true;
}
else
{
e.IsValid = false;
}
}
else {
e.IsValid = true;
}
}
Note: This is not written in any IDE so I can't be sure about the syntax.
Before processing the form, you could check (from the server code) whether the required option in the radiobuttonlist is checked. If not, set the Enabled property of the requiredfieldvalidators to False.

Need help with making label of repeater visible and link button hidden in code behind

aspx page:-
<asp:Repeater ID="rptAdd" OnItemCommand="rptAdd_ItemCommand" runat="server">
<ItemTemplate>
<td>
<asp:LinkButton ID="lnkBill" Text="Make Default" runat="server" Visible="true" CommandName="DefaultBill"></asp:LinkButton>
<asp:Label ID="labelBill" Text="Yes" Visible="false" runat="server"></asp:Label>
</td>
</ItemTemplate>
</asp:Repeater>
Code Behind:-
protected void rptAdd_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "DefaultBill")
{
Users objBill = new Users();
objBill.IsDefault = true;
e.Item.FindControl("labelBill").Visible=true;
e.Item.FindControl("lnkBill").Visible = false;
}
}
In code behind intellisense is not detecting "labelBill" and "lnkBill"..what could be wrong ?
Also need to know...that's how u access controls in a repeater ?? like using findControl() ...right ?
[EDIT]
Changed code as follows..still not working...
((Label)e.Item.FindControl("labelBill")).Visible=true;
((LinkButton)e.Item.FindControl("lnkBill")).Visible = false;
Why wont intellisense detect these two IDs??
The problem is that your controls are inside a repeater, the find control wont search recursively. Try this instead.
rptAdd.FindControl("labelBull").Visible = true;

Categories

Resources