I have a GridView that displays records that are either the number 1 or 0.
How can I convert the record into a check box which is checked if the value is 1 or unchecked if the value is 0?
<asp:GridView ID="gvStations" runat="server">
<columns>
<asp:templatefield headertext="Type" sortexpression="TypeDesc">
<edititemtemplate>
<asp:CheckBox ID="cbTypeEdit" runat="server" Text='<%# Bind("TypeDesc") />
</edititemtemplate>
<itemtemplate>
<asp:CheckBox ID="cbType" runat="server" Text='<%# Bind("TypeDesc") ></asp:CheckBox>
</itemtemplate>
<itemstyle horizontalalign="Center" />
</asp:templatefield>
<asp:templatefield headertext="Type 2" sortexpression="TypeDesc2">
<edititemtemplate>
<asp:CheckBox ID="cbType2Edit" runat="server" Text='<%# Bind("TypeDesc2") />
</edititemtemplate>
<itemtemplate>
<asp:CheckBox ID="cbType2" runat="server" Text='<%# Bind("TypeDesc2") ></asp:CheckBox>
</itemtemplate>
<itemstyle horizontalalign="Center" />
</asp:templatefield>
</columns>
</asp:GridView>
Right now I can change them to an X if its a 1 and a "blank" if its a 0.
protected void gvStations_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i <= this.gvStations.Rows.Count - 1; i++)//from here down changes the 1's to X's and O's to blanks.
{
for (int j = 0; j <= this.gvStations.Columns.Count - 1; j++)
{
if (j != 1 && j != 2)
{
if (this.gvStations.Rows[i].Cells[j].Text == "1")
{
this.gvStations.Rows[i].Cells[j].Text = "X";
}
else if (this.gvStations.Rows[i].Cells[j].Text == "0")
{
this.gvStations.Rows[i].Cells[j].Text = " ";
}
}
}
}
}
For display you can go as simple as a single comparison of the binded value:
<asp:CheckBox ID="cbTypeEdit" runat="server"
Checked='<%# (int)Eval("TypeDesc") == 1 %>'/>
For handling editing of the grid row I am afraid you need to handle the GridView's RowUpdated event and convert the values manually.
I think that should be:
<asp:CheckBox ID="cbTypeEdit" runat="server" Text='<%# Bind("TypeDesc") %>' Checked="<%# (Int)Eval("TypeDesc") == 0 ? false : true %>" />
A simple helper function would be better as you have TypeDesc and TypeDesc2.
Markup
Checked='<%# SetCheckedStatus(Bind("TypeDesc")) %>'
Checked='<%# SetCheckedStatus(Bind("TypeDesc2")) %>'
Code-behind
protected bool SetCheckedStatus(object typeDesc)
{
var isChecked = false;
var intValue = 0;
if (typeDesc != null)
{
int.TryParse(typeDesc.ToString(), out intValue);
if (intValue == 1) { isChecked = true; }
}
return isChecked;
}
Much cleaner markup this way
Related
I have a Data grid that has Item Templates with Labels in it:
<asp:datagrid id="ID" runat="server" Width="641px" CellPadding="2" PageSize="2" DataKeyField="IDs"
AutoGenerateColumns="False" ShowFooter="True" BorderColor="AliceBlue" OnItemDataBound="ID_ItemDataBound" >
<SelectedItemStyle ForeColor="HighlightText" BackColor="Highlight"> </SelectedItemStyle>
<AlternatingItemStyle BackColor="WhiteSmoke">
</AlternatingItemStyle>
<HeaderStyle Font-Bold="True" BackColor="AliceBlue">
</HeaderStyle>
<FooterStyle Font-Bold="True" BackColor="AliceBlue">
</FooterStyle>
<Columns>
<ItemTemplate>
<asp:label BorderStyle=None Visible='<%# ReverseBool(Convert.ToBoolean(DataBinder.Eval(Container, "DataItem.IsCompleteOrNot"))) %>' runat="server" ID="dataScore" Text='<%# DataBinder.Eval(Container, "DataItem.dataScore" ) %>'>
</asp:label>
<asp:label BorderStyle=None Text='<%# GetCompleteIncomplete(Convert.ToInt32(DataBinder.Eval(Container, "DataItem.dataScore")!=null)) %>' Visible='<%# DataBinder.Eval(Container, "DataItem.IsCompleteOrNot") %>' id="txtIsComplete" runat="server">
</asp:label>
</ItemTemplate>
</columns>
And I am trying to Set the 0s to blank instead of showing 0 in the DataGrid so on ItemData bound I get the Label like this and trying to set the value to null:
if ((e.Item.ItemType == ListItemType.Item) ||
(e.Item.ItemType == ListItemType.AlternatingItem))
{
Label dataScore = (Label)e.Item.FindControl("dataScore"); // Gets that Label
Label txtIsComplete = (Label)e.Item.FindControl("txtIsComplete");
if(dataScore .Text == "0")
{
dataScore.Text = string.Empty; // Tried
}
You can write a function to analyse the value of DataBinder.Eval
Private String MyFunction(String value)
{
Return value == "0" ? String.Empty : value;
}
<asp:label BorderStyle=None Visible='<%# ReverseBool(Convert.ToBoolean(DataBinder.Eval(Container, "DataItem.IsCompleteOrNot"))) %>' runat="server" ID="dataScore" Text='<%# MyFunction(DataBinder.Eval(Container, "DataItem.dataScore" )) %>'>
I have a data Grid and there are ItemTamplate and in there are 2 Labels and they both contains some data in it.
I want to be able to loop through the whole GridView and see if any label contains the work Keyboarding and if it does change the value of the second label from Incomplete to To fails or Pass.
Here is the Code.
<asp:datagrid id="dgData" runat="server" Width="658px" CellPadding="2" PageSize="2" DataKeyField="ID"
AutoGenerateColumns="False" ShowFooter="True" BorderColor="AliceBlue" OnItemDataBound="dgData_ItemDataBound">
<SelectedItemStyle ForeColor="HighlightText" BackColor="Highlight"></SelectedItemStyle>
<AlternatingItemStyle BackColor="WhiteSmoke"></AlternatingItemStyle>
<HeaderStyle Font-Bold="True" BackColor="AliceBlue"></HeaderStyle>
<FooterStyle Font-Bold="True" BackColor="AliceBlue"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="ID" Visible="False"></asp:BoundColumn>
<asp:BoundColumn DataField="Name" HeaderText="" ItemStyle-VerticalAlign="Top"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="Term 1" ItemStyle-Wrap="True">
<ItemTemplate>
<asp:label BorderStyle=None Visible='<%# ReverseBool(Convert.ToBoolean(DataBinder.Eval(Container, "DataItem.IsCompleteOrNot"))) %>' runat="server" ID="edit_Score" Text='<%# DataBinder.Eval(Container, "DataItem.Score" ) %>'>
</asp:label>
<asp:label BorderStyle=None Text='<%# GetCompleteIncomplete(Convert.ToInt32(DataBinder.Eval(Container, "DataItem.Score"))) %>' Visible='<%# DataBinder.Eval(Container, "DataItem.IsCompleteOrNot") %>' id="txtIsComplete" runat="server">
</asp:label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
Now the c# the Call to the server GetCompleteIncomplete is a method in the c# that looks at it if its 1 its Complete if its 0 its in complete:
protected string GetCompleteIncomplete(int iScore)
{
if (iScore == 0)
{
return "Incomplete";
}
return "Complete";
}
This return the Value to the Label and shows like this.
But I want to change that InComplete/Compete to Fail/Pass only if the First Label is Keyboarding other lines could stay InComplete or Complete.
Try below code in your itemdatabound event:
if ((e.Item.ItemType == ListItemType.Item) ||
(e.Item.ItemType == ListItemType.AlternatingItem))
{
Label edit_Score = (Label)e.Item.FindControl("edit_Score");
Label txtIsComplete = (Label)e.Item.FindControl("txtIsComplete");
if (edit_Score.Text == "Keyboarding")
{
if (txtIsComplete.Text == "Complete")
{
txtIsComplete.Text = "Pass";
}
else if(txtIsComplete.Text == "InComplete")
{
txtIsComplete.Text = "Fail";
}
}
}
I have a gridview with many columns and rows. I need to get the Checkbox Status for each one of the Template fields from the gridview.
I know I can achieve this by getting each individual:
CheckBox cbTrans = (CheckBox)gvStations.Rows[rowindex].FindControl("cbTaxEdit");
CheckBox cbReg = (CheckBox)gvStations.Rows[rowindex].FindControl("cbRegEdit");
If I have 20 template fields how can I get all of them one at a time. My idea is to get one a time in a for loop and perform an operation for each checkbox.
//Something along this lines but I know I can't use J here
for (int i = 0; i <= this.gvStations.Rows.Count - 1; i++)
{
for (int j = 0; j <= this.gvSta.Columns.Count - 1; j++)
{
//I WANT TO GO THRU EACH COLUMN, J can't be used here, throws error
CheckBox cbox = (CheckBox)gvStations.Rows[i].FindControl(j);
if(cbox.Checked)
{
//Perform Operation
}
}
}
Gridview
<asp:TemplateField HeaderText="TAX" SortExpression="Taxes">
<EditItemTemplate>
<asp:CheckBox ID="cbTaxEdit" runat="server" Checked='<%# (int)Eval("Taxes") == 1 %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbTax" runat="server" Enabled="false" Checked='<%# (int)Eval("Taxes") == 1 %>'>
</asp:CheckBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<%--Registrations--%>
<asp:TemplateField HeaderText="REG" SortExpression="Registrations">
<EditItemTemplate>
<asp:CheckBox ID="cbRegEdit" runat="server" Checked='<%# (int)Eval("Registrations") == 1 %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbReg" runat="server" Enabled="false" Checked='<%# (int)Eval("Registrations") == 1 %>'>
</asp:CheckBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="BTRColumn" SortExpression="BTR">
<EditItemTemplate>
<asp:CheckBox ID="cbBTREdit" runat="server" Checked='<%# (int)Eval("BTR") == 1 %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbBTR" runat="server" Enabled="false" Checked='<%# (int)Eval("BTR") == 1 %>'>
</asp:CheckBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
Posted it as a comment but meant to post it as an answer haha! Been a long day.
I would loop through the check boxes and gather the IDs for them in a list. Lets call list "CheckBoxIDs". I would then do this:
CheckBox cbox = (CheckBox)gvStations.Rows[i].FindControl(CheckBoxIDs[j]);
I am using javascript to make unchecked GridView .
But whenever I try, I cannot make unchecked it.
function UncheckedItemsCheckBox(CheckboxID) {
var checkbox = document.getElementById(CheckboxID);
checkbox.checked = false;
alert(checkbox.id + " : " + checkbox.name + " : " + checkbox.checked);
}
Here is the output.
---------------------------
Message from webpage
---------------------------
GridView1_ctl02_txtDoseQty : GridView1$ctl02$txtDoseQty : false
---------------------------
OK
---------------------------
Even though "checkbox.checked" return me "false" as output message shown, but at the gridview checkbox is still checked.
Could anyone please give me suggestion?
What may be happening is that your CheckBoxID is wrong, and therefore returning the wrong element.
In JavaScript, saying checkbox.checked = false; will, if this object did not previously have a checked property, add one to the object, with the value provided. So, if your CheckBoxID is in fact wrong, it's no surprise your alert shows false; any non-null element you pull back with getElementById will allow you to add a checked property to it.
More specifically, in asp.net when you create a checkbox column, like this
<asp:CheckBoxField Text="Hello" DataField="foo" />
it renders html like this:
<span class="aspNetDisabled">
<input id="gv_ctl00_0" type="checkbox" name="gv$ctl02$ctl00" disabled="disabled">
<label for="gv_ctl00_0">Hello</label>
</span>
A couple possibilities:
The id you're getting may be of the span, on which you're adding a checked property.
You're setting the checkbox to be checked, but since it's disabled, it's not updating its state -- ok, it looks like disabled checkboxes can have their checked properties updated. Hopefully #1 is your problem.
A good place to start debugging would be to change your function to this
function UncheckedItemsCheckBox(CheckboxID) {
var checkbox = document.getElementById(CheckboxID);
alert(checkbox.checked); // <------- should display false, but will
// display undefined if this element is
// something other than a checkbox
checkbox.checked = false;
alert(checkbox.id + " : " + checkbox.name + " : " + checkbox.checked);
}
Are you trying to check or uncheck the checkboxes in a GridView.
If yes then you can try this simple code.
Here we have the javascript function which will called , when the header checkbox is clicked
<script type="text/javascript">
function Check_All(ChkBoxHeader)
{
//First Access the GridView Control
var gridview = document.getElementById('<%=GridEmployees.ClientID %>');
//Now get the all the Input type elements in the GridView
var AllInputsElements = gridview.getElementsByTagName('input');
var TotalInputs = AllInputsElements.length;
//Now we have to find the checkboxes in the rows.
for(var i=0;i< TotalInputs ; i++ )
{
if(AllInputsElements[i].type =='checkbox')
{
AllInputsElements[i].checked = ChkBoxHeader.checked;
}
}
}
The GridView will look like this
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkRecords" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="CheckHeader" runat="server" onclick="Check_All(this);" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I hope that this will help you.
Javascript for Check and uncheck the Checkboxes in gridView
<script language="javascript" type="text/javascript">
var TotalChkBx;
var Counter;
var TotalUnChkBx;
var UnCounter;
window.onload = function () {
//Get total no. of CheckBoxes in side the GridView.
TotalChkBx = parseInt('<%= this.GridView1.Rows.Count %>');
//Get total no. of checked CheckBoxes in side the GridView.
Counter = 0;
}
function HeaderClick(CheckBox) {
//Get target base & child control.
var TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
var TargetChildControl = "chkBxSelect";
//Get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
//Checked/Unchecked all the checkBoxes in side the GridView.
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
Inputs[n].checked = CheckBox.checked;
//Reset Counter
Counter = CheckBox.checked ? TotalChkBx : 0;
}
function ChildClick(CheckBox, HCheckBox) {
//get target base & child control.
var HeaderCheckBox = document.getElementById(HCheckBox);
//Modifiy Counter;
if (CheckBox.checked && Counter < TotalChkBx)
Counter++;
else if (Counter > 0)
Counter--;
//Change state of the header CheckBox.
if (Counter < TotalChkBx)
HeaderCheckBox.checked = false;
else if (Counter == TotalChkBx)
HeaderCheckBox.checked = true;
}
</script>
In GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#006699"
AlternatingRowStyle-ForeColor="#FFFFFF"
>
<Columns >
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBxSelect" runat="server" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Serial Number">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Name" DataField="uname" />
<asp:BoundField HeaderText="Pass" DataField="upass"/>
</Columns>
</asp:GridView>
Try this One
$(document).ready(function () {
$("#headercheck").click(function () {
var ischecked;
if (this.checked == true) {
ischecked = true;
}
else {
ischecked = false;
}
$('<%="#"+GridViewClass1.ClientID%> input:checkbox').attr('checked', $(this).is(':checked'))
});
});
headercheck is my chcekboxid.
I have used something like this to check and uncheck the checkbox in my code. Hope it helps you.
<script language="javascript" type="text/javascript">
// function Search()
// {
// alert("hi");
// }
function SearchValidation() {
var str = "";
var flag;
var count = 0;
// alert("Hi");'txtFirstName'
if (document.getElementById('<%=ddlProjectName.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
count++;
// alert(count);
}
if (document.getElementById('<%=ddlUsers.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
count++;
}
if (document.getElementById('<%=ddlEmployee.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
count++;
}
if (document.getElementById('<%=txtFromDate.ClientID%>').value == "") {
str += "Enter Fromdate \n";
flag = false;
count++;
}
else {
var input = document.getElementById('<%=txtFromDate.ClientID%>');
var validformat = /\d{2}\/\d{2}\/\d{4}$/;
if (!validformat.test(input.value)) {
str += "Invalid Fromdate Format. Please correct and submit again. \n";
flag = false;
}
else {
}
}
if (document.getElementById('<%=txtToDate.ClientID%>').value == "") {
str += "Enter Todate \n";
flag = false;
count++;
}
else {
var inputTo = document.getElementById('<%=txtToDate.ClientID%>');
var validTo = /\d{2}\/\d{2}\/\d{4}$/;
if (!validTo.test(inputTo.value)) {
str += "Invalid Todate Format. Please correct and submit again. \n";
flag = false;
}
else {
}
}
if (count == 5) {
alert("Select any one search criteria.");
return false;
}
else {
return true;
}
}
function ExportToExcelValidation() {
var str = "";
var flag;
// alert("Hi");'txtFirstName'
if (document.getElementById('<%=ddlProjectName.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
}
if (document.getElementById('<%=txtFromDate.ClientID%>').value == "") {
str += "Enter Fromdate \n";
flag = false;
}
else {
var input = document.getElementById('<%=txtFromDate.ClientID%>');
var validformat = /\d{2}\/\d{2}\/\d{4}$/;
if (!validformat.test(input.value)) {
str += "Invalid Fromdate Format. Please correct and submit again. \n";
flag = false;
}
}
if (document.getElementById('<%=txtToDate.ClientID%>').value == "") {
str += "Enter Todate \n";
flag = false;
}
else {
var inputTo = document.getElementById('<%=txtToDate.ClientID%>');
var validTo = /\d{2}\/\d{2}\/\d{4}$/;
if (!validTo.test(inputTo.value)) {
str += "Invalid Todate Format. Please correct and submit again. \n";
flag = false;
}
}
if (flag == false) {
alert(str);
return flag;
}
else {
return flag;
}
}
function CheckValidation() {
if (confirm("Are you sure you want to delete this ?"))
return true;
else
return false;
}
function CheckAll(oCheckbox) {
var GridView2 = document.getElementById("<%=gvLeads.ClientID %>");
for (i = 1; i < GridView2.rows.length; i++) {
GridView2.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = oCheckbox.checked;
// alert(GridView2.rows[i].cells[0].getElementsByTagName("INPUT")[0]);
}
}
function CheckIndividual(oCheck) {
var GridView2 = document.getElementById("<%=gvLeads.ClientID %>");
var checkedCount = 0;
for (i = 1; i < GridView2.rows.length; i++) {
if (GridView2.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == true) {
checkedCount++;
}
}
if (checkedCount == GridView2.rows.length - 1) {
GridView2.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = oCheck.checked;
}
else {
GridView2.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = false;
}
}
</script>
<%----%>
<%-- --%>
' runat="server" Visible="false" />
' runat="server" Visible="false" />
' runat="server" Visible="false" />
<%--onclick="fnCheckAll(this);"--%>
<%--
' runat="server" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<%-- <asp:TemplateField HeaderText="Project Id">
<ItemTemplate>
<asp:Label ID="lblProjectId" Text='<%#Eval("ProjectId") %>' runat="server" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Project Name">
<ItemTemplate>
<asp:Label ID="lblProjectName" Text='<%#Eval("ProjectName") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lead Name">
<ItemTemplate>
<asp:Label ID="lblLeadName" Text='<%#Eval("LeadName") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:Label ID="lblEmployeeName" Text='<%#Eval("EmployeeName") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="Lead Id">
<ItemTemplate>
<asp:Label ID="lblAddedUserName" Text='<%#Eval("LeadId") %>' runat="server" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="From Date">
<ItemTemplate>
<asp:Label ID="lblFromDate" Text='<%#Eval("FromDate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="To Date">
<ItemTemplate>
<asp:Label ID="lblToDate" Text='<%#Eval("ToDate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Added UserName">
<ItemTemplate>
<asp:Label ID="lblCreatedBy" Text='<%#Eval("CreatedBy") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created Date">
<ItemTemplate>
<asp:Label ID="lblCreatedDate" Text='<%#Eval("CreatedDate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Label ID="lblLeadId" Text='<%#Eval("LeadId") %>' runat="server" Visible="false" />
<asp:Label ID="lblProjectId" Text='<%#Eval("ProjectId") %>' runat="server" Visible="false" />
<asp:Label ID="lblEmployeeId" Text='<%#Eval("EmployeeId") %>' runat="server" Visible="false" />
<asp:Label ID="lblEdit" Text='<%#Eval("Id") %>' runat="server" Visible="false" />
<asp:Button ID="btnEdit" runat="server" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Label ID="lblDelete" Text='<%#Eval("Id") %>' runat="server" Visible="false" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="if(!CheckValidation())return false;" />
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#9966FF" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" BorderColor="#0066CC" Font-Bold="False" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="False" ForeColor="#663399" />
<SortedAscendingCellStyle BackColor="#FEFCEB" />
<SortedAscendingHeaderStyle BackColor="#AF0101" />
<SortedDescendingCellStyle BackColor="#F6F0C0" />
<SortedDescendingHeaderStyle BackColor="#7E0000" />
</asp:GridView>
I am using Gridview and using Item Template text box. There are 5 text box and i am adding a new row dynamically on clicking on add row btn. in that row i have adding all text box which is empty. Now i want to validate that text box on btn click next.
now to do it?
I used required field validation its working for first time showing text box but when i am adding a new row text box its not causing the validation, I think there is some other way to give validation for dynamically added text box.
How could i validation my all dynamically added text box
Grid view which i am using..
<Columns >
<asp:TemplateField>
<ItemTemplate>
<div class="otherOthersTd">
<asp:Label ID="lblcnt" ForeColor="#136A96" Text='<%#Eval("Count") %>' runat="server" ></asp:Label>
<asp:Label ID="lblId" runat="server" text='<%#Eval("Id") %>' Visible="false"></asp:Label>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>' Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middle Name">
<ItemTemplate>
<asp:TextBox ID="txtMName" runat="server" Text='<%# Eval("MName") %>'
Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:TextBox ID="txtLName" runat="server" Text='<%# Eval("LName") %>'
Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Degree">
<ItemTemplate>
<asp:TextBox ID="txtDegree" runat="Server" Text='<%# Eval("Degree") %>'
Width="50px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:TextBox ID="txtTitle" runat="Server" Text='<%# Eval("Title") %>' Width="88px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox ID="txtEmail" runat="Server"
Text='<%# Eval("Email") %>' Width="88px" CausesValidation="True" ValidationGroup="a"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegExpr" runat="server" ErrorMessage="Invalid email id" ControlToValidate="txtEmail" ValidationGroup="a" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
<asp:Label ID="revexp" runat="server" > </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Institution">
<ItemTemplate>
<asp:TextBox ID="txtInstitution" runat="server" Text='<%#Eval("Institution") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:Button ID="btnNext" runat="server" ValidationGroup="a" CausesValidation="true" Text="Next" class="next btn" onclick="btnNext_Click"/>
<asp:TemplateField> <ItemTemplate>
<asp:Label ID="lblAuthor" runat="server" Text="Authorerror" Visible="false" ForeColor="Red" Font-Bold="True" Font-Size="X-Large">*</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="false" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<HeaderStyle Font-Bold="false" ForeColor="#136A96" />
</asp:GridView>
my code...
protected void GridView1_OnRowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals(""))
{
lstAuthors = (List<OtherAuthors>)Session["lstAuthors"];
if (lstAuthors.Count == 0)
{
OtherAuthors obj0 = new OtherAuthors();
obj0.Count = "Author 1:";
lstAuthors.Add(obj0);
}
int index=GridView1.Rows.Count-1;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox Name = GridView1.Rows[i].FindControl("txtName") as TextBox;
TextBox MName = GridView1.Rows[i].FindControl("txtMName") as TextBox;
TextBox LName = GridView1.Rows[i].FindControl("txtLName") as TextBox;
TextBox Degree = GridView1.Rows[i].FindControl("txtDegree") as TextBox;
TextBox Title = GridView1.Rows[i].FindControl("txtTitle") as TextBox;
TextBox Email = GridView1.Rows[i].FindControl("txtEmail") as TextBox;
TextBox Institution = GridView1.Rows[i].FindControl("txtInstitution") as TextBox;
if(Name!=null)
{
lstAuthors[i].Name = Name.Text;
lstAuthors[i].MName = MName.Text;
lstAuthors[i].LName = LName.Text;
lstAuthors[i].Degree = Degree.Text;
lstAuthors[i].Title = Title.Text;
lstAuthors[i].Email = Email.Text;
lstAuthors[i].Institution = Institution.Text;
}
}
OtherAuthors obj1 = new OtherAuthors();
obj1.Count = "Author "+(lstAuthors.Count+1).ToString()+":";
obj1.Name="";
lstAuthors.Add(obj1);
GridView1.DataSource = lstAuthors;
GridView1.DataBind();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows.Count - 1 == i)
GridView1.Rows[i].Cells[8].Visible = true;
else
GridView1.Rows[i].Cells[8].Visible = false;
}
Session["lstAuthors"] = lstAuthors;
}
MultipleModalitySelect1.hideChosebutton = true;
}
private bool IsValied()
{
bool error = false;
TextBox Name = GridView1.Rows[0].FindControl("txtName") as TextBox;
TextBox MName = GridView1.Rows[0].FindControl("txtMName") as TextBox;
TextBox LName = GridView1.Rows[0].FindControl("txtLName") as TextBox;
TextBox Degree = GridView1.Rows[0].FindControl("txtDegree") as TextBox;
TextBox Title = GridView1.Rows[0].FindControl("txtTitle") as TextBox;
TextBox Email = GridView1.Rows[0].FindControl("txtEmail") as TextBox;
TextBox Institution = GridView1.Rows[0].FindControl("txtInstitution") as TextBox;
Label lblAuthor = GridView1.Rows[0].FindControl("lblAuthor") as Label;
if (Name.Text.Length == 0 || LName.Text.Length == 0 || Degree.Text.Length == 0 ||Title.Text.Length == 0 || Email.Text.Length == 0 || Institution.Text.Length == 0)
{
lblAuthor.Visible = true;
error = true;
}
else
{
lblAuthor.Visible = false;
}
}
You have used the validation group's ValidationGroup="a" on your Next button, but you have not used that on the Required Field Validator. But you have used it in the Email validator.
You have to be consistent with the Validation control and whether to put validation on all controls and button controls for it to work.
<asp:Button ID="btnNext" runat="server" ValidationGroup="a" CausesValidation="true" Text="Next" class="next btn" onclick="btnNext_Click"/>
I think you should start a new page and test with a much smaller case scenario and get that working first. Then add more boxes.
If you still need help with that smaller page, post it for help - it will be easier for us to understand it.