Enable RequiredFieldValidator if TextBox is not empty - c#

can you help me with this simple problem of mine in asp.net,
I have 3 textboxes; Txt1 Txt2 txt3
If txt1 is not empty, txt2 and txt3 requiredvalidator should be enabled.
if txt1 is empty, txt2 and txt3 requiredvalidator should not be enabled,
Here's the requirement, once txt1 has a value, txt2 and txt3 should be a required field.
can someone help me with this??
Thank you so much.
Can somebody check this code for me? THANK YOU so much
<script type="text/javascript" language="javascript">
function FatherClientValidate(oSrc, args) {
var textBox = document.getElementById('<%=FatherName.ClientID%>');
if (textBox.value != '') {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "#ff0000";
args.IsValid = true;
}
else {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "White";
args.IsValid = false;
}
}
</script>

You can use CustomValidators for Txt2 txt3 , On server validation event of custom validator you can check like below
void ServerValidation (object source, ServerValidateEventArgs args)
{
if (!string.IsNullOrEmpty(Txt1.Text))
args.IsValid = !string.IsNullOrEmpty(args.Value);
}
In client side validation
<script language="javascript">
function ClientValidate(source, arguments)
{
var textBox = document.getElementById('<%=Txt1.ClientID%>');
if (textBox.value !== "" ){
arguments.IsValid = (args.value !== "");
} else {
arguments.IsValid = false;
}
}
</script>

Related

How can I conditionally prevent a form from submitting with server-side/code-behind?

When my "submit" (Save) button is clicked, one thing it does is verifies that the two "totals" vals match, and returns if they don't, fingerwagging the user with a red 'bad boy!' message:
message = new LiteralControl();
AddVerticalSpace();
Controls.Add(message);
decimal? paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
if ((null == paymentTot) || (paymentTot < 0))
{
paymentTot = 0M;
}
decimal? grandTot = TryConvertToDecimal(boxGrandTotal.Text);
if ((null == grandTot) || (grandTot < 0))
{
grandTot = 0M;
}
if (grandTot != paymentTot)
{
AddVerticalSpace();
message.Text = "<span style='color:red'>Total and Payment Total do not match; Please enter the same amount for both values and try again.</span>";
return;
}
What I intend with the "return" is that the submit is aborted; yet, with the code above, the form is still submitted - it reverts to its initial appearance/state. How can I conditionally prevent this automatic submit behavior?
UPDATE
This is for Tyree Jackson:
Here's the server-side save button. First, it is conditionally dynamically created and configured thus:
if (AnyCheckboxSelected())
{
// Create Save button
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
AddVerticalSpace();
}
...and here is the event handler:
protected void btnSave_Click(object sender, EventArgs e)
{
LiteralControl message = null;
try
{
fullAddressChosen = rbFullAddress.Checked;
paymentToAnIndividualDropDownChosen = rbPaymentToIndividual.Checked;
paymentToAVendorDropDownChosen = rbPaymentToVendor.Checked;
message = new LiteralControl();
AddVerticalSpace();
Controls.Add(message);
decimal? paymentTot = TryConvertToDecimal(boxPaymentAmount.Text);
if ((null == paymentTot) || (paymentTot < 0))
{
paymentTot = 0M;
}
decimal? grandTot = TryConvertToDecimal(boxGrandTotal.Text);
if ((null == grandTot) || (grandTot < 0))
{
grandTot = 0M;
}
if (grandTot != paymentTot)
{
AddVerticalSpace();
message.Text = "<span style='color:red'>Total and Payment Total do not match; Please enter the same amount for both values and try again.</span>";
return;
}
ConditionallyCreateList();
SaveInputToList();
listOfListItems = ReadFromList();
message.Text = "Saving the data has been successful";
// Re-visiblize any rows with vals
if (RowContainsVals(3))
{
foapalrow3.Style["display"] = "table-row";
}
if (RowContainsVals(4))
{
foapalrow4.Style["display"] = "table-row";
}
if (RowContainsVals(5))
{
foapalrow5.Style["display"] = "table-row";
}
if (RowContainsVals(6))
{
foapalrow6.Style["display"] = "table-row";
}
AddVerticalSpace();
//CreatePDFGenButton();
GeneratePDFAndMsg();
btnGeneratePDF.Visible = true;
AddVerticalSpace();
GenerateLegalNotice();
}
catch (Exception ex)
{
message.Text = String.Format("Exception occurred: {0}", ex.Message);
}
}
First Default.aspx source:
<script type="text/javascript" language="javascript">
function validateData() {
var payment = parseFloat(document.getElementById('boxPaymentAmount').value).toFixed(2);
var total = parseFloat(document.getElementById('boxGrandTotal').value).toFixed(2);
if (payment == null) payment = 0;
if (total == null) total = 0;
if (payment == total) {
return true;
} else {
alert('Total and Payment Total do not match. Please enter the same amount for both values and try again!');
return false;
}
}
</script>
<asp:TextBox ID="boxPaymentAmount" runat="server"></asp:TextBox><br />
<asp:TextBox ID="boxGrandTotal" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSave" runat="server" Text="Button" OnClientClick="return validateData();" OnClick="btnSave_Click" />
And code for Default.aspx.cs:
public partial class Default : System.Web.UI.Page
{
protected void btnSave_Click(object sender, EventArgs e)
{
//TODO: do your stuff here...
}
}
If you are talking about preventing a form from submitting in a web browser, you should use client side code (i.e. JavaScript) for that. Even if there was a way to do it in code behind, it would just be translated into client side code. Otherwise, the form will submit even if it retains the edited values.

call OnClientClick and Onclick together in c# Button Event

I have a Asp.Net c# application in which, having Logout Button on mAsterpage.
I am trying to alert confirmation window on click of LogOut. If i choose Yes, then I will redirect it into Log-in Page.
So I have tried below. OnClient Click I called below JavaScript Function.
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
On Button Click I have wriiten Below code.
protected void ImgbtnLogOut_Click(object sender, ImageClickEventArgs e)
{
try
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
Session.Clear();
Session.Abandon();
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
//Server.Transfer(ConfigurationManager.AppSettings["LogoutURL"].ToString());
}
else
{
//Do Nothing
}
}
catch (Exception ex)
{
}
finally
{
}
}
I am getting an error Unable to evaluate Expression, The code is Optimized....error in below line. And Page is not being redirected to required page.
Response.Redirect(ConfigurationManager.AppSettings["LogoutURL"].ToString());
can anyone please suggest, how can i achieve that.
This confirm box help you to get correct response with having Ajax.
java script code for geting confirm value.
<script type="text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you want to proceed continue ?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
On C# Code for geting exect data.
string confirmValue = Request.Form["confirm_value"];
string[] Value_Confirm = confirmValue.Split(',');
if (Value_Confirm[Value_Confirm.Length-1] == "Yes")
{}
or check here : http://www.codeproject.com/Answers/1070495/Ask-yes-no-cancel-window-in-csharp#answer6

ScriptManager.RegisterStartupScript doesn't fire in ItemDataBound of RadGrid

Why is ScriptManager.RegisterStartupScript not firing on the ItemDataBound event of my RadGrid?
protected void gridMonitorVisibilityConfiguration_OnItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
try
{
if (e.Item is Telerik.Web.UI.GridDataItem)
{
if (!IsPostBack)
{
Telerik.Web.UI.GridDataItem item = (Telerik.Web.UI.GridDataItem)e.Item;
Label lblnoAll = (Label)item["Configuration"].FindControl("lblNoAcces");
Label lblView = (Label)item["Configuration"].FindControl("lblview");
Label lblViewMod = (Label)item["Configuration"].FindControl("lblviewMod");
Label lblUser = (Label)item["Configuration"].FindControl("lblUserRoleText");
HiddenField hdnFlag = (HiddenField)item["Configuration"].FindControl("hdnrdFlagValue");
RadioButton rdno = (RadioButton)item["Configuration"].FindControl("rdoNoAccess");
RadioButton rdview = (RadioButton)item["Configuration"].FindControl("rdoViewOnly");
RadioButton rdVM = (RadioButton)item["Configuration"].FindControl("rdoViewModify");
DataTable dts = Facade.Monitoring.SelectVisibilityConfiguration(UserProfile.UserLogin, hdnMonitoringID.Value).Tables[0];
if (dts.Rows.Count > 0)
{
if (!Boolean.Parse(dts.Rows[0]["VisibilityFlag"].ToString()))
{
rdShared.Checked = false;
lblUser.Style["color"] = "grey";
lblshared.Style["color"] = "grey";
lblnoAll.Style["color"] = "grey";
lblView.Style["color"] = "grey";
lblViewMod.Style["color"] = "grey";
//disable img
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "DisableDivImg",
"<script type='text/javascript'>$('[ID*=DivImgSelect]').off('click');</script>", false);
//disable text
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "DisableDivText",
"<script type='text/javascript'>$('[ID*=DivText]').off('click');</script>", false);
// gridMonitorVisibilityConfiguration.Enabled = false;
gridMonitorVisibilityConfiguration.ShowFooter = false;
SetScreen();
}
else
{
rdShared.Checked = true;
BindGridMonitorVisibilityConfiguration();
gridMonitorVisibilityConfiguration.ShowFooter = true;
rdPrivate.Checked = false;
}
}
if (hdnFlag.Value == "2")
{
rdVM.Checked = true;
}
else if (hdnFlag.Value == "1")
{
rdview.Checked = true;
}
else if (hdnFlag.Value == "0")
{
rdno.Checked = true;
}
}
}
}
catch (Exception ex)
{
SetException(ex);
}
}
When data loads in condition disable so jQuery on the page will be disabled. On this case I put ScriptManager on ItemDataBound which is getdata in a first load.
If you set the last parameter of RegisterStartupScript set to true, you will not have to add the script tags. It looks like you are trying to find the element DivText, so try this:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "DisableDivText",
"$find('DivText').off('click');", true);
try to use this one
RadScriptManager.RegisterStartupScript(Page, Page.GetType(), "1", "Sys.Application.add_load(function(){{alert('success');}}, 0);", true);

How to get listbox id inside the listview in javascript

I want to to get listbox id inside the listview in javascript.
This is my Javascript:
<script>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(
function (sender, e) {
var control = $find('<%= results.ClientID %>');
if (e.get_postBackElement().id =="<%=this.results.ClientID%>") {
$get("divvv").style.display = "none";
}
else {
$get("divvv").style.display = "block";
}
});
</script>
results is my listbox id but it is in the listview so that i couldn't get the listbox it directly as specified above.It shows Error.
Please hel me.Thanks in advance
i havent tested but you can try this
function (sender, e) {
var control = $find('<%= ((ListBox)MyListView.FindControl("myListBox")).ClientID %>');
if (e.get_postBackElement().id =='<%= ((ListBox)MyListView.FindControl("myListBox")).ClientID %>') {
$get("divvv").style.display = "none";
}
else {
$get("divvv").style.display = "block";
}

Using PostBackUrl, Getting PreviousPage.Control()

I'm using PostBackUrl to post my control from a "firstwebpage.aspx" to a "secondwebpage.aspx" so that I would be able to generate some configuration files.
I do understand that I can make use of PreviousPage.FindControl("myControlId") method in my secondwebpage.aspx to get my control from "firstwebpage.aspx"and hence grab my data and it worked.
However, it seems that this method does not work on controls which I generated programmically during runtime while populating them in a table in my firstwebpage.aspx.
I also tried using this function Response.Write("--" + Request["TextBox1"].ToString() + "--");
And although this statement do printout the text in the textfield on TextBox1, it only return me the string value of textbox1. I am unable to cast it to a textbox control in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
My question is, how can I actually access the control which i generated programmically in "firstwebpage.aspx" on "secondwebpage.aspx"?
Please advice!
thanks alot!
//my panel and button in aspx
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Generate Xml" PostBackUrl="~/WebForm2.aspx" onclick="Button1_Click" />
//this is my function to insert a line into the panel
public void createfilerow(string b, string path, bool x86check, bool x86enable, bool x64check, bool x64enable)
{
Label blank4 = new Label();
blank4.ID = "blank4";
blank4.Text = "";
Panel2.Controls.Add(blank4);
CheckBox c = new CheckBox();
c.Text = b.Replace(path, "");
c.Checked = true;
c.ID = "1a";
Panel2.Controls.Add(c);
CheckBox d = new CheckBox();
d.Checked = x86check;
d.Enabled = x86enable;
d.ID = "1b";
Panel2.Controls.Add(d);
CheckBox e = new CheckBox();
e.Checked = x64check;
e.Enabled = x64enable;
e.ID = "1c";
Panel2.Controls.Add(e);
}
//my virtual path in WebForm2.aspx
<%# PreviousPageType VirtualPath="~/WebForm1.aspx" %>
//my pageload handler
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
CheckBox tempCheckbox = (CheckBox)Page.PreviousPage.FindControl("1a");
Button1.Text = tempCheckbox.Text;
}
}
//handler which will populate the panel upon clicking
protected void Button7_Click(object sender, EventArgs e)
{
//get foldername
if (!Directory.Exists(#"myfilepath" + TextBox2.Text))
{
//folder does not exist
//do required actions
return;
}
string[] x86files = null;
string[] x64files = null;
string[] x86filespath = null;
string[] x64filespath = null;
ArrayList common = new ArrayList();
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x86"))
x86files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x86");
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x64"))
x64files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x64");
//some codes to convert x64files and x86files to string[]
//The header for Panel, 4 column
Label FL = new Label();
FL.ID = "flavourid";
FL.Text = "Flavour";
Panel2.Controls.Add(FL);
Label filetext = new Label();
filetext.ID = "filenamelabel";
filetext.Text = "File(s)";
Panel2.Controls.Add(filetext);
Label label86 = new Label();
label86.ID = "label86";
label86.Text = "x86";
Panel2.Controls.Add(label86);
Label label64 = new Label();
label64.ID = "label64";
label64.Text = "x64";
Panel2.Controls.Add(label64);
//a for loop determine number of times codes have to be run
for (int a = 0; a < num; a++)
{
ArrayList location = new ArrayList();
if (//this iteration had to be run)
{
string path = null;
switch (//id of this iteration)
{
case id:
path = some network address
}
//check the current version of iternation
string version = //version type;
//get the platform of the version
string platform = //platform
if (curent version = certain type)
{
//do what is required.
//build a list
}
else
{
//normal routine
//do what is required
//build a list
}
//populating the panel with data from list
createflavourheader(a);
//create dynamic checkboxes according to the list
foreach(string s in list)
//createrow parameter is by version type and platform
createfilerow(readin, path, true, true, false, false);
}
}
}
form1.Controls.Add(Panel2);
}
Sorry can't show you the full code as it is long and I believe it should be confidential even though i wrote them all
Yes you can access, Below is an example
// On Page1.aspx I have a button for postback
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
PostBackUrl="~/Page2.aspx" />
// Page1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
TextBox t = new TextBox(); // created a TextBox
t.ID = "myTextBox"; // assigned an ID
form1.Controls.Add(t); // Add to form
}
Now on the second page I will get the value of TextBox as
// Page2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
// OR
string myTextBoxValue = Request.Form["myTextBox"];
}
Updated Answer:
Panel myPanel = new Panel();
myPanel.ID = "myPanel";
TextBox t = new TextBox();
t.ID = "myTextBox";
myPanel.Controls.Add(t);
TextBox t1 = new TextBox();
t1.ID = "myTextBox1";
myPanel.Controls.Add(t1);
// Add all your child controls to your panel and at the end add your panel to your form
form1.Controls.Add(myPanel);
// on the processing page you can get the values as
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
string myTextBoxValue = Request.Form["myTextBox1"];
}
I also tried using this function Response.Write("--" +
Request["TextBox1"].ToString() + "--"); And although this statement do
printout the text in the textfield on TextBox1, it only return me the
string value of textbox1. I am unable to cast it to a textbox control
in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
Hi lw,
I think you may try passing the type of control (e.g. 'tb') together with the content and creating a new object (e.g. TextBox) and assign it to templtexBox object.
My 20 cents.
Andy

Categories

Resources