TextBox Custom Web Control and JavaScript Client Validation - c#

I have created custom web control textbox which is working fine and its code is as below:
public class ReqTextBox : TextBox
{
private RequiredFieldValidator req;
public string ErrMsg { get; set; }
protected override void OnInit(EventArgs e)
{
this.CssClass = "inp-form";
req = new RequiredFieldValidator();
req.ControlToValidate = this.ID;
req.ErrorMessage = string.IsNullOrEmpty(this.ErrMsg) ? "*" : this.ErrMsg;
req.Display = ValidatorDisplay.Dynamic;
//req.EnableClientScript = true;
if (!string.IsNullOrEmpty(this.ValidationGroup))
req.ValidationGroup = this.ValidationGroup;
Controls.Add(req);
//base.OnInit(e);
}
protected override void Render(HtmlTextWriter w)
{
base.Render(w);
req.RenderControl(w);
}
}
This is working fine with following code:
<Mas:ReqTextBox runat="server" ID="txtCustBankCode" Width="236px" ValidationGroup="vmas" ErrMsg="Enter BankName"></Mas:ReqTextBox>
<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />
Here it works fine. Now if i add onclientclick event on button then it will not check if textbox is empty or not. In both return true and false in Valid() function it's not working.
<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" onClientClick="return Valid();" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />
What am i missing...?
req.EnableclientScript = true/false;
did not help me.
Need Help.
Thanks.
EDIT: I need to use this Customcontrol, so that user need to enter some data and for those entered data, i need to validate with javascript function. Sorry for late EDIt.

Use customvalidator with custom clientvalidation function:
<script type="text/javascript">
function ClientValidate(source, arguments) {
if (arguments.Value === "foo") {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Invalid entry" ControlToValidate="TextBox1"
ClientValidationFunction="ClientValidate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
Read more from here .

Related

copy text from one textbox to another on checkbox event asp.net c#

I have two address fields which has 46 textboxes and each one accepts only one character.
For eg.
Address
Line1 : 1.2.3.4....46
Line2 : 1.2.3.4...46
Now on checkbox oncheckchanged event,
I want to copy each character from textbox to another respectively and if checkbox is not checked then line one should be remained as it is.
How to accomplish this?
I tried googling but didn't help much.
<asp:TextBox runat="server" ID="line1_1" MaxLength="1" ></asp:TextBox><br/>
<asp:CheckBox runat="server" ID="if_same" Text="Same" OnCheckedChanged="if_same_CheckedChanged" AutoPostBack="true" />
<asp:TextBox runat="server" ID="line2_1" MaxLength="1" ></asp:TextBox><asp:TextBox runat="server" ID="line2_46" MaxLength="1" ></asp:TextBox>
protected void if_same_CheckedChanged(object sender, EventArgs e)
{
set_per_local();
}
public void set_per_local()
{
if (if_same.Checked == true)
{
checkIfNullEmpty();
disablelocal();
string line1_address = string.Concat(line1_1.Text,line1_46.Text);
try
{
for (int i = 0; i < line1_address.Length; i++)
{
line2_1.Text = line1_address[0].ToString();
line2_46.Text = line1_address[45].ToString();
}
}
catch (Exception)
{
throw;
}
}
else
{
Enablelocal();
}
}
public void checkIfNullEmpty()
{
if (string.IsNullOrEmpty(line1_1.Text)) line1_1.Text = " ";
if (string.IsNullOrEmpty(line1_46.Text)) line1_46.Text = " ";
}
public void disablelocal()
{
local_line1_address1.Enabled = false;
local_line1_address46.Enabled = false;
}
public void enablelocal()
{
local_line1_address1.Enabled = true;
local_line1_address46.Enabled = true;
}
I think this could be a better candidate for a client-side javascript or jQuery etc. Also, if you have followed a logical pattern for naming those 46 textboxes, in your javascript you could hook into the checkbox.changed event and start a loop walking each of the source fields and replace the target field textbox with the source value. Something like
<script>
$(".checkbox").change(function() {
if(this.checked) {
alltextboxes();
}
});
function copy alltextboxes()
{
for (int i = 0; i < 46; i++)
{
document.getElementById(tgtTbox+i).value = document.getElementById(srcTbox+i).value
}
}
</script>
Disclaimer: I have not tested this code though. I just typed it into the answer. based on your requirement, this code may need small modifications. Just note that this only works if your naming convention for the textbox labels follow a pattern (like "SourceText1, SourceText2, TargetText1, TargetText2 etc.").
I found this site more helpful.
http://www.dotnetspark.com/kb/3125-how-to-copy-textbox---text-to-another-one.aspx
<asp:TextBox runat="server" ID="TextBox1" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox2" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox3" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox4" MaxLength="1" size="1"></asp:TextBox>
<asp:CheckBox runat="server" ID="CheckBox1" Text="Same as above" onclick="CopyText()" />
<asp:TextBox runat="server" ID="iBox1" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox2" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox3" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox4" MaxLength="1" size="1"></asp:TextBox>
<script type="text/javascript">
function CopyText() {
var cb = document.getElementById('CheckBox1');
var tb1 = document.getElementById('TextBox1');
var tb2 = document.getElementById('TextBox2');
var tb3 = document.getElementById('TextBox3');
var tb4 = document.getElementById('TextBox4');
var tb11 = document.getElementById('iBox1');
var tb12 = document.getElementById('iBox2');
var tb13 = document.getElementById('iBox3');
var tb14 = document.getElementById('iBox4');
if (cb.checked) {
tb11.value = tb1.value;
tb12.value = tb2.value;
tb13.value = tb3.value;
tb14.value = tb4.value; }
else {
tb11.value = '';
tb12.value = '';
tb13.value = '';
tb14.value = ''; }
}
}
<script>

C# ASP.NET using Boolean variable from code behind in ASP.NET

I know how to use a String variable from code to behind and say display that string on the web page. What I want to do is similar except that instead of displaying a string, I want to pass the boolean value from code behind, to the ASP.NET page so that its' true / false value can control the Print button (true / false) in the ReportViewer. My Diagnostic works in that it displays the string "True" or "False", which ever is correct. The "ShowPrintButton" and "ShowExportControls" just don't work though and the buttons are not enabled. What do I need to do here? I think the value is being passed but perhaps it's being passed as a string and I need to do something to make it pass as a Boolean....
Here's the code ...
Code Behind:
//Variables
public Boolean exportEnabled { get; set; }
public Boolean printEnabled { get; set; }
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
// Add a handler for SubreportProcessing
reportViewerPrintAndExport.LocalReport.SubreportProcessing +=
new SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
if (!IsPostBack)
{
// Display the report
DisplayReport(Session[SessionKeys.KEY_CERT_NO].ToString(), (CalibrationType)Session[SessionKeys.KEY_CERT_TYPE]);
}
DataBind();
}
private void DisplayReport(string certNo, CalibrationType calType)
{
string[] rolesList = Roles.GetRolesForUser();
//manage print and export buttons.
if ((rolesList.Contains("admin")) || (rolesList.Contains("Admin")))
{
exportEnabled = true;
printEnabled = true;
}
else if ((rolesList.Contains("Operator")) || (rolesList.Contains("operator")))
{
exportEnabled = false;
printEnabled = false;
}
}
aspx:
<!-- DIAGNOSTIC -->
<asp:label runat="server" text="-" /><asp:label runat="server" text="<%# printEnabled %>" /><asp:label runat="server" text="-" />
<asp:Panel ID="ReportPanelPrintAndExport" runat="server" HorizontalAlign="Left">
<!--Why does this not work? -->
<rsweb:ReportViewer ShowPrintButton="<%# printEnabled %>" ShowExportControls="<%# exportEnabled %>" ID="reportViewerPrintAndExport" runat="server" Height="100%" Width="100%"
ShowBackButton="False" ZoomMode="FullPage"
ShowRefreshButton="False" ProcessingMode="Local">
</rsweb:ReportViewer>
In your code behind simply set that property wherever you want to
if ((rolesList.Contains("admin")) || (rolesList.Contains("Admin")))
{
reportViewerPrintAndExport.ShowPrintButton = true;
reportViewerPrintAndExport.ShowExportControls = true;
}
else if ((rolesList.Contains("Operator")) || (rolesList.Contains("operator")))
{
reportViewerPrintAndExport.ShowPrintButton = false;
reportViewerPrintAndExport.ShowExportControls = false;
}
There is no need to try to do this on the client side.

Textbox not getting readonly

I have a textbox, on click, it allows you to select date from calendar control. If the date is deleted, it should uncheck the checkbox available just next to the textbox.
With below code, I am able to achieve everything other than making the textbox readonly so that user is not able to type anything. Also, once the text is selected, checkbox gets checked but when text is deleted the checkbox doesn't get unchecked.
Can anyone suggest what needs I might be doing wrong here ?
<asp:CalendarExtender ID="CalForDate" runat="server" TargetControlID="txtDate" Format="MM/dd/yyyy" PopupPosition="BottomLeft" DefaultView="Days"></asp:CalendarExtender>
<asp:TextBox runat="server" ID="txtDate" AutoPostBack="true" EnableViewState = "false" onKeyPress="javascript:return ChkCheckBox()" OnTextChanged="txtDate_OnTextChanged"></asp:TextBox>
The javascript code:
function ChkCheckBox() {
var txtDate = document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_txtDate').value;
if (txtDate.length == 9) {
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = true;
}
else
{
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = false;
}
In pageload I have added:
if (!IsPostBack){
txtDate.Attributes.Add("readonly", "readonly");}
And on text changed:
public void txtDate_OnTextChanged(object o, EventArgs e){
if (!(string.IsNullOrEmpty(txtDate.Text)))
{
chkDate.Visible = true;
chkDate.Checked = true;
}
else
{
chkDate.Visible = true;
chkDate.Checked = false;
} }
You can easily achieve this using jquery. I am sending you the sample code. Please don't hesitate to ask further assistance if needed.
<script type="text/javascript">
$(document).ready(function () {
$('#txtDate').on('change', function () {
//console.log('Tested');
if ($(this).val().toString().trim() != '') {
$('[Id*=ckTest]').attr('checked', 'checked');
}
else {
$('[Id*=ckTest]').removeAttr('checked');
}
});
$('#btnClear').click(function () {
$('#txtDate').val('');
$('#txtDate').trigger('change');
});
});
</script>
The code file is as below.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true" ClientIDMode="Static"></asp:TextBox>
<asp:CheckBox ID="ckTest" runat="server" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" />
<button id="btnClear">Clear</button>
</div>
</form>
Just add jquery to project i used
jquery-2.1.4.min.js

Button Click fires before custom validation occurs

I have this form with a custom validator, and Button.
But, my custom Validator shows error only after button click.
This is my validator, Button and code behind.
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="User Name cannot be Empty!" ForeColor="Red"
onservervalidate="CustomValidator1_ServerValidate"
ControlToValidate="userNameTxt" ValidateEmptyText="True"
ValidationGroup="save-valid"></asp:CustomValidator>
<asp:Button ID="saveButton" runat="server" Text="Save" CssClass="save-button"
onclick="saveButton_Click" TabIndex="7" ValidationGroup="save-valid" />
This is my code behind.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (IsUserValid(userNameTxt.Text))
{
CustomValidator1.ErrorMessage = "User Name cannot be Empty!";
args.IsValid = false;
}
else
args.IsValid = true;
}
protected void saveButton_Click(object sender, EventArgs e)
{
//This code executes regardless of CUstom Validator
}
You can try to use client side validation.
<script type="text/jscript">
function textBoxControl(source,arguments){
if(arguments.Value.length >0) //or control things (e.g. at least 6 character)
arguments.isValid = true;
else
arguments.isValid = false;
}
<script>
Code behind is like below.
<asp:TextBox ID="userNameTxt" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ErrorMessage="CustomValidator"
onservervalidate="CustomValidator1_ServerValidate"
ControlToValidate="userNameTxt"
ClientValidationFunction="textBoxControl"></asp:CustomValidator>
When I put the below code inside Save Button click, the problem gets solved.
if (!Page.IsValid)
return;

Custom validator getting invoked onclick of all controls on the page

i have written a custom validation function to check if a panel is displayed
i want the function to be invoked onclick of NEXT button.
But instead it gets invoked onclick of every button on the page.
Here is the code:
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
and this is the button code onclick of which it should be invoked.
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
if i set Controltovalidate="btnNext" then it again throws me error.
"btnNext cannot be validated".
You need to hook it to the right element.
document.getElementById("btnNext").onclick = function() {
//Do Your Stuff Here
};
Angela
Hey i did a very simple solution to my problem.
first is the java script code that ws getting invoked onclick of evry button on the page.
function Validate(sender, args)
{
if (document.getElementById("Panel1").style.display == 'none') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
Then on the Next button:
<asp:Button ID="btnNext" runat="server" Text="Next" Font-Bold="True" CssClass="InputButton" OnClick="btnNext_Click" />
<asp:CustomValidator ID="cvValidate" runat="server" ErrorMessage="Panel has no data." ClientValidationFunction="Validate" Display="none" EnableViewState="false"></asp:CustomValidator>
and for the rest of buttons i did set causesvalidation=false property. with this the function wwas getting invoked only on Next button

Categories