Asp.net Gridview CompareValidator - c#

I have a GridView with multiple rows (records).
<asp:DropDownList ID="DDLActionStatus" runat="server" DataSourceID="LDSActionStatus" AppendDataBoundItems="True" DataTextField="Title" DataValueField="ReportActionStatusID" SelectedValue='<%# Bind("ReportActionStatusID") %>' Enabled='<%# (int)Eval("ReportActionStatusID") == 1 %>' Width="100%" />
<asp:Button ID="BtnActionStatus" runat="server" CommandName="Update" Text="Save & Close" OnClientClick="return confirm('Are you sure? Once set, this can not be changed.')" Width="100%" />
<asp:CompareValidator ID="CVActionStatus" runat="server" Operator="NotEqual" ValueToCompare="1" Type="Integer" ControlToValidate="DDLActionStatus" SetFocusOnError="true" ErrorMessage="Must set one of the Completion statuses" />
It works fine for one row, however if there are multiple rows it validates all rows together.
I understand it happens because the ControlToValidate="DDLActionStatus" repets for each row.
I tried to set the ID like ID="DDLActionStatus<%# Eval('ReportActionStatusID') %>" and the ControlToValidate="DDLActionStatus<%# Eval('ReportActionStatusID') %>", but it doesn't work.
I know I could write a custom validation, but is there an easy solution that doesn't require a custom validation?
What I need is to each row be validate independent.
Thanks for help.

The issue is not with the ControlToValidate property. Add a ValidationGroup property to each control in a row with same value. But, make sure to keep it unique for all rows in your GridView. See following example.
<asp:DropDownList ID="DDLActionStatus" runat="server" ValidationGroup="MyGroup1" DataSourceID="LDSActionStatus" AppendDataBoundItems="True" DataTextField="Title" DataValueField="ReportActionStatusID" SelectedValue='<%# Bind("ReportActionStatusID") %>' Enabled='<%# (int)Eval("ReportActionStatusID") == 1 %>' Width="100%" />
<asp:Button ID="BtnActionStatus" runat="server" ValidationGroup="MyGroup1" CommandName="Update" Text="Save & Close" OnClientClick="return confirm('Are you sure? Once set, this can not be changed.')" Width="100%" />
<asp:CompareValidator ID="CVActionStatus" runat="server" ValidationGroup="MyGroup1" Operator="NotEqual" ValueToCompare="1" Type="Integer" ControlToValidate="DDLActionStatus" SetFocusOnError="true" ErrorMessage="Must set one of the Completion statuses" />
Make sure ValidationGroup is different for each row.
All the best!

Related

Place RequiredFieldValidator inside a asp:DataList

I have a problem with placing RequiredFieldValidator into a DataList, and some assistance would be greatly appreciated.
Problem description:
When I place the <asp:RequiredFieldValidator>inside the <ItemTemplate> and run the page I get the following error page:
When I place it outside of it, the page works with no error, but obviously it cannot identify witch <asp:TextBox> does not have content in it, before it is posted back. And I would like to make where it is able to tell if a particular text box in the data list does not have text entered.
Here is the markup: (the Image src attribute is not implemented yet)
<asp:DataList ID="imageUploadRoster" runat="server"
DataSourceID="ImageUploadRosterDataSource" RepeatDirection="Horizontal" RepeatColumns="5" HorizontalAlign="Left">
<HeaderTemplate>
<h3>Set Image Names</h3>
</HeaderTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Height="180px" Width="180px" />
<ItemTemplate>
<div class="imageSetNameDiv">
<asp:HiddenField ID="ImageId" runat="server" Value='<%# Eval("ImageId") %>' />
<asp:HiddenField ID="ImageMimeTypeLabel" runat="server" Value='<%# Eval("ImageMimeType") %>' />
<asp:Image ID="ImageThumbnailLabel" runat="server" Src='<%# Eval("ImageThumbnail") %>' Width="120px" Height="120px" />
<br />
<asp:RequiredFieldValidator ID="imageNameRequired" runat="server"
ControlToValidate="ImageName" ErrorMessage="RequiredFieldValidator"
ValidationGroup="imageUploadValid">
</asp:RequiredFieldValidator>
<asp:TextBox ID="ImageName" runat="server" Text='<%# Eval("ImageName") %>' />
<br />
<hr />
<asp:Button ID="removeImage" runat="server" Text="Remove" CommandName="delete" CommandArgument='<%# Eval("ImageId") %>' />
</div>
</ItemTemplate>
</asp:DataList>
Thank you in advance for any assistance.
Peter
This error happens when ASP.NET encounters two controls with the same ID on the page. I guess for some reason in your case validators for each item get the same ID. Setting the following property:
ClientIDMode="Predictable"
for validator should fix it. This mode makes sure control in databound context gets correct ID.

Using a field mask and forcing the cursor to the left

This is not identical to this question, but it's very similar.
I'm using ASP.Net and need to more or less do the same thing, but was hoping it can be done on the ASP side.
My relevant code is such:
<td style="line-height: 230%;">
<asp:TextBox ID="txtePro" runat="server" CssClass="textbox" Font-Size="Small" Height="18px" Width="100px" Visible="False" Wrap="False" OnTextChanged="txtEPro_OnLeave" AutoPostBack="true"></asp:TextBox>
<asp:MaskedEditExtender ID="MeeePro" runat="server" Mask="9999999" MaskType="None" TargetControlID="txtePro" PromptCharacter="_" />
<asp:MaskedEditExtender ID="MeePRD" runat="server" Mask="999999" MaskType="None" TargetControlID="txtePro" PromptCharacter="_" />
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtePro" ID="RevePro" ValidationExpression="^[\s\S]{7,7}$" runat="server" ErrorMessage="7 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator>
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtePro" ID="RevPRD" ValidationExpression="^[\s\S]{6,}$" runat="server" ErrorMessage="6 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator>
<asp:TextBox ID="hdntxtePro" runat="server" CssClass="textbox" Font-Size="Small" Height="18px" Width="100px" Visible="False" Wrap="False"></asp:TextBox>
<asp:DropDownList ID="ddlCIT" runat="server" AutoPostBack="True" CssClass="textbox" Visible="false" Height="20px" OnSelectedIndexChanged="ddlCIT_SelectedIndexChanged" Width="100px"></asp:DropDownList>
<asp:TextBox ID="txtCIT" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" Wrap="False"></asp:TextBox>
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtCIT" ID="RevCIT" ValidationExpression="^[\s\S]{4,}$" runat="server" ErrorMessage="4 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator>
<asp:MaskedEditExtender ID="meeCIT" runat="server" MaskType="Number" Mask="99.99" TargetControlID="txtCIT" PromptCharacter="_" InputDirection="LeftToRight" />
<asp:TextBox ID="txtClientID" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" Wrap="False" OnTextChanged="txtClientID_OnLeave" AutoPostBack="true" MaxLength="5"></asp:TextBox>
<asp:MaskedEditExtender ID="meeClientID" runat="server" MaskType="Number" Mask="99999" TargetControlID="txtClientID" PromptCharacter="_" InputDirection="LeftToRight" AutoComplete="False" UserTimeFormat="TwentyFourHour"/>
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtClientID" ID="RevClientID" ValidationExpression="^[\s\S]{5,5}$" runat="server" ErrorMessage="5 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator>
<asp:TextBox ID="hdntxtClientID" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" Wrap="False"></asp:TextBox>
<asp:TextBox ID="txtElasID" runat="server" CssClass="textbox" Height="18px" Width="100px" Wrap="False" Visible="False" Font-Size="Small"></asp:TextBox>
<asp:MaskedEditExtender ID="meeElas" runat="server" MaskType="None" Mask="99999999" TargetControlID="txtElasID" PromptCharacter="_" />
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtElasID" ID="RevElasID" ValidationExpression="^[\s\S]{8,}$" runat="server" ErrorMessage="8 Digits required." ForeColor="White"></asp:RegularExpressionValidator>
<asp:TextBox ID="txtEffDate" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" TextMode="Date" Wrap="False"></asp:TextBox>
<asp:RangeValidator ID="rvDate" runat="server" ControlToValidate="txtEffDate" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic" ForeColor="White"></asp:RangeValidator>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtEffDate" Format="MM/dd/yyyy"></asp:CalendarExtender>
</td>
As in the linked question, my problem is that when a user clicks inside the text box, they're sometimes starting in the middle and I need the cursor to be forced all the way to the left. Is there a way to force the cursor all the way to the left from within ASP, or is this something that can only be done in the code-behind?
You can achieve that using javascript and jQuery by setting the SelectionRange to 0,0 on the mouseup event:
$(document).ready(function(){
$(".resetCursor").mouseup(function () {
this.setSelectionRange(0,0);
});
});
http://jsfiddle.net/6m8stbo7/1/
Then add the class resetCursor to the TextBox Controls you want to extend with this behavior.
<asp:TextBox ID="txtePro" runat="server"
CssClass="textbox resetCursor"
Font-Size="Small"
Height="18px"
Width="100px"
Visible="False"
Wrap="False"
OnTextChanged="txtEPro_OnLeave"
AutoPostBack="true">
</asp:TextBox>
Explanation:
resetCursor is a css stylesheet class that is used by jQuery to select the specific DOM-Elements. It is common practice to use css classes to "declare" certain behavior on a set of DOM-Elements and then use jquery to "activate" that behavior in one go. Edit: Note that resetCursor is an arbitrary name, you could have chosen another name as you please.
Here is a good introduction to the basic jQuery selectors (I'm using the Class-Selector in this example):
http://api.jquery.com/category/selectors/basic-css-selectors/
This answer uses jQuery - I hope you know it, otherwise this no good:) In case you know it - using answer by Ovm2 just fix your ASP.NET markup like CssClass="textbox resetCursor" or do it programmatically with jQuery with .addClass() so
$(document).ready(function(){//once DOM is loaded
$(".textbox").addClass('resetCursor');
$(".resetCursor").mouseup(function () {
this.setSelectionRange(0,0);
});
});
In case you aren't familiar with jQuery - well, you have to start learning it asap!:)
P.S. Initially I intended to add the comment to answer by Ovm, but I failed to format code sample with mini-markup there. And don't forget to learn\refresh info about using CSS selectors as this is the ultra important, well, it is simply essential for having good times not only with jQuery, but with HTML at all. Hope that helps:)
You can use createTextRange method in javascript to move cursor postion. Following function will help you to move position to start.
function setCaretPosition(elemId) {
var inputEle = document.getElementById(elemId);
if (inputEle != null) {
if (inputEle.createTextRange) {
var range = inputEle.createTextRange();
range.move('character', -1);
range.select();
}
else {
if (inputEle.selectionStart) {
inputEle.focus();
inputEle.setSelectionRange(0, 1);
}
else
inputEle.focus();
}
}
}
You can use TextMode="Multiline" property for Textbox

C# Edit Command Name in Gridview

In my gridView I've inserted the edit command name for every single row.
Now I need when the database value of myDate is not null stopping the edit in this row.
I tried this solution, but in GV see the icon stop.gif when the database value of myDate is not null, but if click in stop.gif the edit row is open, why?
Can you help me?
Thanks in advance.
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<center>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"
ImageUrl='<%#(String.IsNullOrEmpty(Eval("myDate").ToString()) ? "/Images/edit.gif" : "/Images/stop.gif")%>'
ToolTip="Edit" /></center>
</ItemTemplate>
<EditItemTemplate>
<center>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="/Images/update.gif"
ToolTip="Update" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="/Images/cancel.gif"
ToolTip="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
If you just make the image url blank, it does not mean that you are not rendering the control. The button will still render. What you could do instead is like below
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"
ImageUrl='/Images/stop.gif'
Visbile = '<%#Eval("myDate").HasValue %>'
ToolTip="Edit" />

Error: 'this._targetEl.value.length' is null or not an object ASP.NET

I'm trying to bind the selected value from the date picker to an asp textbox but I have this Error: 'this._targetEl.value.length' is null or not an object.
Here's the code:
<InsertItemTemplate>
Book Title:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="booktitleDataSource" DataTextField="booktitle"
DataValueField="bookid" SelectedValue='<%# Bind("bookid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="booktitleDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [bookid], [booktitle] FROM [TblBooks]">
</asp:SqlDataSource>
<br />
Employee PIN:
<asp:TextBox ID="employeeidTextBox" runat="server"
Text='<%# Bind("employeeid") %>' />
<br />
Department:
<asp:TextBox ID="departmentTextBox" runat="server"
Text='<%# Bind("department") %>' />
<br />
Date borrowed:
<asp:TextBox ID="dateborrowedTextBox" runat="server" Text='<%# Bind("dateborrowed") %>' />
<%--<input type="text" name="dateborrowedTextBox" readonly="readonly" id="dateborrowedTextBox">--%>
Date Picker
<br />
<asp:Button ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:Button ID="InsertCancelButton" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
It was working when I
tried using <input type="text" name="dateborrowed" readonly="readonly" id="dateborrowedTextBox"> but when I tried using the asp:TextBox I cant pass the selected value from date picker to the textbox. So where did I go wrong? Is there a way to program the date picker link to call the popup calendar? (its in Java btw)
Help would be much appreciated!
Thanks in advance.
Nested controls have their ID/name attributes overwritten with an absolute unique id/name when rendered. When your javascript is attempting to reference the TextBox its name won't actually be 'dateborrowedTextBox' it will be something like '...$ctl00$dateborrowedTextBox'.
If your javascript is finding the control by name, this might clear up the issue:
Date Picker
Otherwise try this if its finding the control by id:
Date Picker
Found the solution. I think it can only read asp.net syntax not classic asp.
<asp:TextBox ID="reservedateTextBox" runat="server" Text='<%# Bind("reservedate") %>' />
<%--Date Picker--%>
Date Picker

Binding a Java Date Picker to a textbox in formview ASP.NET C#

I'm having some problem binding the value of a date picker to a textbox in formview asp.net. I've tried to a put a date picker in ASP.NET and JavaScript which calls on a class file in calendar.css so far it can display the date but if I tried to insert it to a record it always return null. So how can I bind it so it can add the date value to the record?
Help would be much appreciated.
Thanks in advance ;)
Here's a sample of my code. I want to bind the 'input text' to the 'dateborrowedTextBox'
<InsertItemTemplate>
Book Title:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="booktitleDataSource" DataTextField="booktitle"
DataValueField="bookid" SelectedValue='<%# Bind("bookid", "{0}") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="booktitleDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT [bookid], [booktitle] FROM [TblBooks]">
</asp:SqlDataSource>
<br />
Employee PIN:
<asp:TextBox ID="employeeidTextBox" runat="server"
Text='<%# Bind("employeeid") %>' />
<br />
Department:
<asp:TextBox ID="departmentTextBox" runat="server"
Text='<%# Bind("department") %>' />
<br />
Date borrowed:
<%--<asp:TextBox ID="dateborrowedTextBox" runat="server"
Text='<%# Bind("dateborrowed") %>' />--%>
<input type="text" name="dateborrowedTextBox" readonly="readonly" id="dateborrowedTextBox">
<a href="#" onclick="cdp1.showCalendar(this, 'dateborrowedTextBox'); return false;">Date Picker
</a>
<br />
<asp:Button ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:Button ID="InsertCancelButton" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
The client-side IDs of the ASP.NET controls are not going to be translated as cleanly as you are hoping.
You need to do one of two things, both of which can be found here.
Date Picker
Or, you could add a Link control and set the actions that way (the link I gave you does it with an image control). It's up to you.
Just found my answer. ASP.NET cant read Javascript normally so CT100 and some dollar sign will do the trick ;)
Date Picker

Categories