Confirm dialog with ok/cancel - c#

I am using a WebForms GridView control. When a user clicks "Update" on a row, I want to check the values they entered against some other records.
From that, if I return true, I'd like to display a confirm dialog asking the user if they'd like to continue with their update.
A javascript confirm dialog probably won't work because I don't always want to show this dialog, only when the values entered meet a certain condition.
Any suggestions?

I would suggest using the RowDataBound event to check for those conditions and add the confirmation dialog where needed.
EDIT : Compare dates and show a confirmation if they're different
See this jsFiddle for a demonstration.
<script type="text/javascript">
validateInput = function(inputDate, compareDate, confirmButtonID) {
var confirmButton = document.getElementById(confirmButtonID);
if (confirmButton) {
$(confirmButton).one("click", function() {
var result = dates.compare(inputDate, compareDate);
if (result != 0){ //change to suit your needs
return confirm("Are you sure you want to save these changes?");
}
return true;
});
}
}
</script>
And here's the code for the dates class used for the comparison (link):
<script type="text/javascript">
var dates = {
convert:function(d) {
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
</script>
In the RowDataBound event of the GridView, assign the onchange function for each row:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
var inputCtrl = e.Row.FindControl("txtEnteredDate") as TextBox;
if (inputCtrl != null)
{
var updateButtonCtrl = e.Row.FindControl("btnUpdate") as Button;
if (updateButtonCtrl != null)
{
inputCtrl.Attributes["onchange"] = string.Format("return validateInput(this.value, '{0}', '{1}');", DataBinder.Eval("DateToCompare"), updateButtonCtrl.ClientID);
}
}
}
jQuery Confirmation Dialog
If you need something more flexible than a regular JavaScript confirm dialog, you can change the above to use the jQuery UI Dialog as a confirmation instead.

If you are using WebForms (?), you need to add some validation controls to the GridView template.
Here is an example from MSDN using a CompareValidator:
<EditItemTemplate>
<asp:TextBox ID="EditUnitPrice" runat="server"
Text='<%# Bind("UnitPrice", "{0:c}") %>'
Columns="6"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="EditUnitPrice"
ErrorMessage="The price must be greater than or equal to zero and
cannot include the currency symbol"
Operator="GreaterThanEqual" Type="Currency"
ValueToCompare="0">*</asp:CompareValidator>
</EditItemTemplate>

Related

How to make textbox visible when previous textbox contains text

I have a WebForm in which i need to place around 30 textboxes mainly to enter barcode scanned data. I am making only the first textbox visible and i want the next textbox to be visible only when the previous textbox is filled with some text. I tried using 'If' condition as well in the textbox on selected change but it doesn't work. Any solutions?
You should use java-script for this because if you will use server side function for this then It will go to server so many times by this your application performance also will decrease.
So create a java-script function that will accept one argument. This argument will take next text box id (text box u want to display).
call this javascript function like this:- onkeyup="calgrid(this,"TextBox2");"
pass nexttextbox id in place of TextBox2...
<script type="text/javascript" language="javascript">
function calgrid(firsttextbox,nexttextbox)
{
var id=firsttextbox.id;
var lastindex= id.lastIndexOf("_");
var strclnt=id.slice(0,lastindex+1);
var txtboxvalue=document.getElementById(firsttextbox).value;
if(txtboxvalue!="")
{
document.getElementById(strclnt+nexttextbox).style.visibility='visible';
}
else
{
document.getElementById(strclnt+nexttextbox).style.display = "none";
}
}
</script>
note:- If you will do visible=false from textbox property then we cannt do visible=true from javascript. So Set style for all textbox style="display:none"
You can resolve your problem by Jquery.
I have make a sample code where i have take four Textbox. Initially only first text box is visible in Web form, when user enter some values in first TextBox next Textbox is automatically display if Previous textbox have a value if not next textbox is not visible.
Sample code is given below :
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
$('input:text:not(:eq(0))').hide()
$('input').on("change paste keyup", function () {
if ($(this).val().length > 0) {
$(this).next().show();
}
else
{
$(this).next().hide();
}
});
I have made sample application for same ,please click on given link for Demo
See Demo application
It's at Client side code so its performance is so fast rather than Server Side.
Please vote me if you feel your problem is resolved by my idea.
I'd name these text boxes similarly like "textbox1", "textbox2", "textbox3" so you can easily find the index of current text box. Then you can use KeyDown event to control what will be shown and what not. This is not a working example but it should give you a good direction.
int currentIndex = 1;
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox t = Controls["TextBox" + (currentIndex + 1).ToString()] as TextBox;
t.Visible = true;
currentIndex +=1;
}
Use can use Keydown event in your first textbox
try this code
initially set flag=1 as first textbox is going to be by default visible
private void visibleTextBox(Control c)
{
int flag = 1;
foreach (Control c1 in c.Controls)
{
if (c1.GetType() == typeof(TextBox))
{
if (flag == 1)
{
((TextBox)c1).Visible = true;
}
else
{
((TextBox)c1).Visible = false;
}
if (((TextBox)c1).Text != "")
{
flag = 1;
}
else
{
flag = 0;
}
}
}
}
Comparatively simple solution in JavaScript. The code should be somehow like this.
Define onchange event on text boxes like this:
<asp:TextBox ID="txt1" runat="server" onchange="show('txt1', 'txt2');"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server" onchange="show('txt2', 'txt3');" Style="visibility: hidden;"></asp:TextBox>
Then use this JavaScript code to show the next TextBox conditionally. Put this code in the head tag of the page:
<script type="text/javascript">
function show(txtCurrent, txtNext) {
var valueCurrent = document.getElementById(txtCurrent).value;
//alert(valueCurrent);
if (valueCurrent.length > 0) {
document.getElementById(txtNext).style.visibility = 'visible';
}
else {
document.getElementById(txtNext).style.visibility = 'hidden';
}
}
</script>

How to clear a textbox on single press of Backspace key using Javascript?

I m working on a web application that contains a text box. The value of text box is filled from Date picker and its property is read only by default. till now everything is working fine. But problem occurs when I press backspace button. Rather than clearing the text box it is redirecting me back on the previous page.
i handled this situation by a javascript function by referring some previous answers on this site.
function allowBackSpace(val) {
var keyCodeEntered = (event.which) ?
event.which :
(window.event.keyCode) ?
window.event.keyCode :
-1;
if (keyCodeEntered == 8) {
$(this).val("");
return true;
}
return false;
}
UPDATE : this function is called from
<asp:TextBox ID="txtDate"
Style="margin-left: 5px; margin-right: 5px"
runat="server"
Width="88px"
onkeypress="return allowBackSpace(this);">
</asp:TextBox>
I m calling this function on key press event of the textbox. The preoblem is that it is allowing only to delete one character at a time.
I wish to clear the whole textbox if user presses backspace button. Stuck here as how to achieve this.
Thanks in advance
Akhil
PS:Any way to achieve this using C# code will also be very helpful.
You are returning true from js function, which also performs its keypress event. So, try with returning false.
You can try the following code:
function allowBackSpace(val) {
var keyCodeEntered =
(event.which) ? event.which :
(window.event.keyCode) ? window.event.keyCode : -1;
if (keyCodeEntered == 8)
{
$(this).val("");
return false;
}
return false; }
Try this function.
$("#txt1").keydown(function(eve){
var keyCodeEntered = eve.keyCode? eve.keyCode : eve.charCode;
if (keyCodeEntered == 8)
{
$(this).val("");
return false;
}
return false;
});
});
Use Jquery
$("#txtDate").keyup(function(event){
if(event.keyCode == 8){
$("#txtDate").val("");
return false;
}
});
function allowBackSpace(e,obj)
{
var evt=e||window.event;
if(evt.keyCode==8)
{
obj.value='';
}
}
Now, use onkeydown event instead of onkeypress
<textarea onkeydown='allowBackSpace(event,this)'></textarea>

How I turn label in asp red

Hi I would like to turn label red in .aspx when user enters wrong answer into textbox.
but not know how, hw I can do this?
You can do this using javascript (call this code from onchange of the textbox):
<label for="myTextBox" id="myLabel">For my textbox</label>
<input id="myTextBox" onchange="ValidateAnswer();">
function ValidateAnswer() {
var txtBox = document.getElementById('myTextBox');
if(txtBox.value != "answer") {
document.getElementById('myLabel').style.color = 'red';
}
}
You can also use the Validator controls if you're using ASP.Net:
<asp:CustomValidator runat="server" ID="cvAnswer"
ControlToValidate="myTextBox"
ErrorMessage="required"
ClientValidationFunction="ValidateAnswer"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="First"
ForeColor="red" >
</asp:CustomValidator>
function ValidateAnswer(sender, args) {
args.IsValid = args.Value != "" && args.Value == "answer here";
if(!args.IsValid) {
document.getElementById('myLabel').style.color = 'red';
}
return;
}
From the server side code:
if(this.txtBox.Text.Length == 0)
{
//no value entered
lblMyLabel.BackColor = Color.Red;
lblMyLabel.Text = "Invalid entry";
}
Client side you can do this:
Markup:
<asp:TextBox onchange="Validate();" runat="server" id="myTextBox"/>
JS:
function Validate()
{
var t = document.getElementByID("myTextBox");
var l = document.getElementByID("myLabel");
if (t.Length == 0)
{
l.style.backgroundColor='red';
}
}
There are multiple options, some server side, and some client side, but in both cases it involves validation. Essentially you are looking to change a css class or other style property on the label.
C# code behind:
if(yourConditionText != "YourExpectedValue")
{
youTextBox.BackColor = System.Drawing.Color.Red;
}
In the Server side button click event (which will be automatically generated when you double click on the button in Design view of the aspx page):
protected void Button_Click(...)
{
if(txtYourTextBox.Text != "YourDesiredValue")
{
lblYourLabel.ForeColor = Color.Red;
}
}
Better still, you could use String.Compare (recommended) as below:
if(string.Compare(txtYourTextBox.Text, "YourDesiredValue") != 0) //0 = Match
{
lblYourLabel.ForeColor = Color.Red; //For backColor set BackColor property
}
Hope it helps!

inline edit control

The label is initialized with the value of the textbox. Upon clicking the label, the textbox is shown. The user can then edit the contents of the textbox. Upon blurring focus, the textbox is hidden and the label shown. Should the user delete the contents of the textbox or only enter whitespace into the textbox, the textbox is not hidden, thus avoiding showing a label with no text. Is there a way to do this ?
Untested, but the general idea should help you out.
HTML:
<asp:TextBox ID="txtA" onblur="txtBlur();" style="display:none;" runat="server"/>
<asp:Label ID="txtA" onclick="txtFocus();" runat="server"/>
Client-side JS:
<script>
var txtA = document.getElementById("<%# txtA.ClientID %>");
var lblA = document.getElementById("<%# lblA.ClientID %>");
function txtBlur()
{
if (txtA.value.trim() != '')
{
lblA.innerText = txtA.value;
lblA.style.display = 'inline';
txtA.style.display = 'none';
}
}
function txtFocus()
{
txtA.value = lblA.innerText;
lblA.style.display = 'none';
txtA.style.display = 'inline';
}
</script>
Check for js validation that textbox is not empty
function Validate()
{
if(document.getElementById("txta").value=="")
{
alert('Please enter the value');
document.getElementById("txta").focus();
return false;
}
}
or you can server side
if (txa.text ="")
{
Response.Write('Text box cannot be empty');
}

Can I do a Date Check on a TextBox with a onBlur event?

I want to do a Date Check on a TextBox with a onBlur event. I am not sure how to check the textbox in javascript on the aspx side. This is what I have so far
TodayDate= new Date();
function checkEnteredDate() {
if (document.getElementById('txtDate') > TodayDate) {
alert("You cannot select a date later than today.");
document.getElementById(TodayDate);
}
}
This is already a javascript function, I just cannot get the value in the textbox for a comparison.
Any suggestions?
You could try passing the "this" to the function:
<asp:TextBox ID="Text1" onblur="CheckEnteredDate(this);" runat="server" />
Edit: Here's how the javascript function would use that (roughly):
function CheckEnteredDate(passed) {
if (new Date(passed.value) > new Date()) {
alert('Date greater than today');
}
}
Use the DateJs library to do date validation on the client-side like this...
function checkEnteredDate() {
var elem = document.getElementById('txtDate');
if(Date.parse(elem.value) > Date.today()) {
alert("You cannot select a date later than today.");
elem.select();
}
}
If you're using Microsoft Ajax, Date parsing is already handled by the provided javascript reference libraries.
<asp:TextBox ID="Text1" onblur="CheckEnteredDate(this);" runat="server" />
Then on the function call:
function CheckEnteredDate(passed) {
var value = Date.parseLocale(passed.value, 'd');
if (isNaN(value))
alert('Not a valid date.');
if (value > new Date())
alert('You cannot select a date later than today.');
}
You should just be able to add a function call to this to the onBlur event for the textbox.
When you pass textbox to document.getElementById, it returns an HTML object not the text inside the textbox. Use value property to get the value entered by the user. See below:
function checkEnteredDate()
{
var inputDate = document.getElementById('txtDate');
if(inputDate == '')
{
alert('You must specify date.');
return false;
}
inputDate = new Date(inputDate);
var today = new Date();
today.setHours(0, 0, 0, 0); //By default today's date will have time portion as well.
if(inputDate > today)
{
alert('You can not select a date later than today');
return false;
}
return true;
}

Categories