Treeview validation - c#

The treeview has leaf node checkboxes.I need to validate the treeview
if atleast one of the node is checked and not more than a specfic(say 3 nodes) number of nodes a user can select.
Note:The Treeview is a asp.net treeview(not an ajax treeview)

Alright, since you didn't mentioned what type of validation you want, I'll do both client side and server side. My TreeView is named tvTest
First, add a CustomValidator to you Asp.Net page:
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ClientValidate"
ErrorMessage="CustomValidator" Display="Dynamic" OnServerValidate="CustomValidator1_ServerValidate">*</asp:CustomValidator>
Note: don't set the ControlToValidate property.
Next, add this script (also to your Asp.Net page) for client side validation:
<script type="text/javascript">
function ClientValidate(source, arguments) {
var treeView = document.getElementById("<%= tvTest.ClientID %>");
var checkBoxes = treeView.getElementsByTagName("input");
var checkedCount = 0;
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
checkedCount++;
}
}
if (checkedCount > 0 && checkedCount < 4) {
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
And last, add this to your code-behind for server side validation:
protected void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args) {
if (tvTest.CheckedNodes.Count > 0 && tvTest.CheckedNodes.Count < 4) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
Of course, you'll want to change the limits for the minimum and maximum number of nodes the user can check.

Related

Uncheck the first checked CheckBox when count exceeds the Maxlimit

I have a CheckBoxList and my requirement is to allow user to select maximum three options(through Javascript) and as soon as he clicks on the fourth one the first selected CheckBox gets unchecked, similarly when he selects the fifth (another) one, the CheckBox which was selected second, gets unchecked and so on. Eventually user is left with only three selected options.
Eg. In the given image if user selects .Net(first),Java(second),PHP(third) and when he selects SQL(fourth), .Net gets unchecked and SQL gets checked. Further when he selects Cloud Computing(fifth), Java gets unchecked.
I have written the following Javascript which works fine for the first scenario and un- checks the first selected item when fourth one is selected but it doesn't work further because counter value again reaches to 4 and cbArray[counter - 4] again tries to uncheck the first box instead of second. How to resolve this problem. Thanks.
My Javascript:
<script type="text/javascript" language="javascript">
function limitChecked(maxCount) {
debugger;
var ocbList = document.getElementById('cbList');
var cbArray = ocbList.getElementsByTagName('input');
var counter = 0;
for (var i = 0; i < cbArray.length; i++) {
if (cbArray[i].checked==true) {
counter++;
if (counter > maxCount) {
cbArray[counter - 4].checked = false;
}
}
}
}
</script>
.aspx code:
<body>
<form id="form1" runat="server">
<div>
Courses:
<asp:CheckBoxList ID="cbList" runat="server" onclick="limitChecked(3)">
<asp:ListItem>.Net</asp:ListItem>
<asp:ListItem>Java</asp:ListItem>
<asp:ListItem>PHP</asp:ListItem>
<asp:ListItem>SQL</asp:ListItem>
<asp:ListItem>Cloud Computing</asp:ListItem>
</asp:CheckBoxList>
</div>
</form>
</body>
As per Trendy's suggestion (McGarnagle's answer also helped) I've come up with this solution, which is working fine for me.
function limitChecked(maxCount) {
debugger;
var ocbList = document.getElementById('cbList');
var cbArray = ocbList.getElementsByTagName('input');
var checkedArray = [];
for (var i = 0; i < cbArray.length; i++) {
if (cbArray[i].checked == true) {
checkedArray.push(i);
if (checkedArray.length > maxCount) {
checkedArray = checkedArray.slice(0);
cbArray[checkedArray[0]].checked = false;
}
}
}
}
You could use push/pop instead of the counter. Using slice(0) allows you to use an array like a FIFO queue:
function limitChecked(maxCount) {
debugger;
var ocbList = document.getElementById('cbList');
var cbArray = ocbList.getElementsByTagName('input');
var checked = [];
for (var i = 0; i < cbArray.length; i++) {
if (cbArray[i].checked==true) {
checked.push(i);
if (checked.length > maxCount) {
cbArray[checked[0]].checked = false;
checked = checked.slice(1);
}
}
}
}

how to show confirmation dialog from drop down list?

i have a grid which display data from database, and i have a custom column in the left side with checkbox, i choose records to be deleted and i have a dropdown list, which will trigger an event in server side to delete records, before i delete those records i want to show a confirmation dialog like "are you sure? with ok and cancel", how to do that? any thought?
i do this :
if(ddlAction.SelectedValue == "Delete")
{
string id = string.Empty;
int i = 0;
List<int> idx = new List<int>();
foreach (GridViewRow rowitem in gvDept.Rows)
{
CheckBox itemchk = (CheckBox)rowitem.FindControl("cbSelectOne");
if (itemchk != null & itemchk.Checked)
{
id += rowitem.Cells[3].Text.ToString() + ',';
idx.Add(i);
}
i = i + 1;
}
id = id.Trim(",".ToCharArray());
List<string> objRemoveKeys = id.Split(',').ToList();
if (objRemoveKeys.Count > 0)
{
ddlAction.Attributes.Add("OnChange", "javascript:return confirmDeletion('Are you sure you would like to remove the selected items?');"); // this part not working.
AirAsiaLinqDataContext LinqDataCtx = new AirAsiaLinqDataContext();
var record = from a in LinqDataCtx.departements
where objRemoveKeys.Contains(a.departementcode)
select a;
LinqDataCtx.departements.DeleteAllOnSubmit(record);
LinqDataCtx.SubmitChanges();
for (int j = 0; j < idx.Count; j++)
{
gvDept.DeleteRow(idx[j]);
}
}
ddlAction.SelectedValue = "";
}
This looks like code-behind (C#) code. Dialogs happen on the client side. You can do this relatively easily with jQuery (or even vanilla JavaScript code), or use something like the Ajax Control Toolkit's ConfirmButton:
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx
For a little more control over the process you can also give JuiceUI a go: http://juiceui.com/controls/dialog
try this
ddlAction.Attributes.Add("onchange", "return confirm('Are you sure you would like to remove the selected items?');");
you should not only show an alert for confirmation but also check if the user has selected some row or not. below code accomplishes both.
javascript function:
function checkIfSelected() {
if (yourGrid.GetSelectedRowCount() == 0) {
alert("You must select atleast one.");
return false;
}
else {
if (confirm("Are you sure you want to proceed?")) { // This is what you want
}
else {
return false;
}
}
}
your dropdownlist:
<asp:DropDownList ID="ddlAction" onChange="javascript:if( checkIfSelected() == false){return false};" AutoPostBack="true" runat="server" OnSelectedIndexChanged="yourID_SelectedIndexChanged">

Server side variable in client side custom validator

I have a custom validator on a page:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ControlToValidate="ddlProposer" ErrorMessage="Please select some values."
Display="Dynamic" onservervalidate="CustomValidator2_ServerValidate"
ClientValidationFunction="CustomValidator2_ClientValidate">
</asp:CustomValidator>
It must be valid, when a server-side list is not empty (or: the ListCount variable > 0). This list may change after the page has been loaded (via buttons on update panel):
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
...
There is no problem with server-side validation:
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = this.ProposersList.Count > 0;
}
The problem is with client-side part. I've been trying something like this:
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var serverVariable = <%= ListCount %>;
alert(serverVariable);
arguments.IsValid = serverVariable > 0;
}
</script>
however, it fires only on first page load, and the ListCount variable is always 0 (so does the serverVariable).
The question is: is there an easy-way to make it working? So the Javascript gets the current value of some server-side variable?
you can use hidden variable on the page level and by setting its value from server side and validate on client side.
<input type="hidden" id="ListCount" runat="server" value="0" />
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
ListCount=value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var count= document.getElementById("ListCount").value;
alert(count);
arguments.IsValid = count > 0;
}
You'll have to do it in plain javascript, and there is no sens of getting the server side variable since it won't be up to date at the moment client validation will be done.
What you need is pass your ddl html element to your CustomValidator2_ClientValidate function and check if it contains option html elements, that should do the trick.

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!

How to make the Default focus in content page from master page

I have masterpage with content place holder. i have contentpage which is using master page . in all my content page i need to default focus on the text box so that the user can directly type in text box instead moving the mouse over the textbox. in some page there is no text box so that i donnot nnet keep default focus over there
Is there any way i can do it in my master page once and can reuse that in all my content page
thank you
try using this...
((TextBox)Master.FindControl("txtRequiredFocus")).Focus();
You could include this in your master page's load event:
// if the ID is constant you can use this:
/*TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.FindControl("myTextBox");
*/
// this will look for the 1st textbox without hardcoding the ID
TextBox textBox = (TextBox)Page.Controls[0]
.FindControl("ContentPlaceHolder1")
.Controls.OfType<TextBox>()
.FirstOrDefault();
if (textBox != null)
{
textBox.Focus();
}
This would match up with a content page that has the following markup:
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:TextBox ID="myTextBox" runat="server" />
</asp:Content>
EDIT: if LINQ isn't an option then you can use this instead:
foreach (Control control in Page.Controls[0].FindControl("ContentPlaceHolder1").Controls)
{
if (control is TextBox)
{
((TextBox)control).Focus();
break;
}
}
Indiscriminate JavaScript approach to selecting the first valid input field on a page:
function SelectFirstInput() {
var bFound = false;
for (f = 0; f < document.forms.length; f++) {
// for each element in each form
for (i = 0; i < document.forms[f].length; i++) {
// if it's not a hidden element
if (document.forms[f][i].type != "hidden") {
// and it's not disabled
if (document.forms[f][i].disabled != true) {
// set the focus to it
document.forms[f][i].focus();
var bFound = true;
}
}
// if found in this element, stop looking
if (bFound == true)
break;
}
// if found in this form, stop looking
if (bFound == true)
break;
}
}
<script language="javascript" type="text/javascript" >
window.onload=function(){
var t= document.getElementById('<%=TextBox1.clientID %>');
t.focus();
}
</script>
If you use jQuery, a possible solution is:
Give the textbox you want to set focus to a special class. "focus" works well for this purpose.
Write code such as the following in your master page or included by your master page in a js script file:
$(document).ready
(
function()
{
//get an array of DOM elements matching the input.focus selector
var focusElements = $("input.focus").get();
//if a focus element exists
if(focusElements.length > 0)
{
focusElements[0].focus();
}
}
);
A similar approach using vanilla JavaScript would be to tag the textbox with a special attribute. Let's use focus.
window.onload = function()
{
//get all input elements
var inputElements = document.getElementsByTagName("input");
var elementToFocus = null;
for(var i = 0; i < inputElements.length; ++i)
{
var focusAttribute = inputElements[i].getAttribute("focus");
if(focusAttribute)
{
elementToFocus = inputElements[i];
break;
}
}
if(elementToFocus)
{
elementToFocus.focus();
}
};
Control masterC =
Page.Master.FindControl("ContentPlaceHolder1");
TextBox TextBox1 =
masterC.FindControl("TextBoxUsername") as TextBox;
TextBox1.Focus();

Categories