Javascript uncheck checkboxs from Asp.net GridView - c#

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>

Related

How to read gridview column and row wise data in asp.net?

I want to read the gridview column data in c#.
I am using C# as a backend and ASP.Net as backend.
front end: asp grid view
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" onrowcommand="GridView2_RowCommand" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="NAME" HeaderText="EVENT NAME" />
<asp:BoundField DataField="TYPE" HeaderText="TYPE OF EVENT" />
<asp:BoundField DataField="desc" HeaderText="DESCRIPTI0ON OF EVENT" />
<asp:TemplateField HeaderText="Poster">
<EditItemTemplate>
<asp:FileUpload ID="FileUpload" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("poster") %>' Height="100px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
**<asp:TemplateField HeaderText="Team Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox" runat="server" ></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox" runat="server" ></asp:TextBox>
</ItemTemplate>**
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" Text="participate" CommandName="participate" HeaderText="participation" />
</Columns>
</asp:GridView>
c# protected void GridView2_RowCommand
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["Event_ManagementConnectionString"].ConnectionString);
SqlCommand cmd;
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow SelectedRow = GridView2.Rows[rowindex];
string id = Convert.ToString(GridView2.DataKeys[rowindex].Values[0]);
string team_name = SelectedRow.Cells[4].Text;
//= Convert.ToString(GridView2.Rows[rowindex].Values[4]);
Response.Write(team_name+"what the hell it is"+ SelectedRow.Cells[0].Text+SelectedRow.Cells[1].Text+ SelectedRow.Cells[2].Text+ SelectedRow.Cells[3].**Text+ SelectedRow.Cells[4].Text**);
if (e.CommandName == "participate")
{
if (team_name == "null")
{
Label3.Text = "Team name cant be blank";
Label3.Visible = true;
}
}
}
}
How to get the team name from the gridview?
I am unable to get data from column 4: SelectedRow.Cells[4].Text;
Team name holds in a textbox control of column 4. so, select team text control and you should get team name as text property of text box. Change code like this:
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow SelectedRow = GridView2.Rows[rowindex];
string id = Convert.ToString(GridView2.DataKeys[rowindex].Values[0]);
TextBox txtteam= (TextBox)SelectedRow.Cells[4].FindControl("TextBox");
string team_name = txtteam.Text;
//= Convert.ToString(GridView2.Rows[rowindex].Values[4]);
Response.Write(team_name + "what the hell it is" + SelectedRow.Cells[0].Text + SelectedRow.Cells[1].Text + SelectedRow.Cells[2].Text + SelectedRow.Cells[3].Text + txtteam.Text);
if (e.CommandName == "participate")
{
if (team_name == "null")
{
Label3.Text = "Team name cant be blank";
Label3.Visible = true;
}
}

Save state of checkbox in gridview when changed to edite mode

When I am clicking on imagebutton in my gridview, some cells become editable
but, it loses all the checkboxs values that in the gridview.
Is there a way to save these values?
I made a function who gets the checkboxes values from my xml but, when I call the function inside the command era it's not working.
When I call that function in other imagebutton command era in the gridview which doesn't make some cells editable, that works and the function runs and the values from the xml shown on the checkboxes.
Thanks
<asp:GridView style="direction:rtl; " ShowHeader="False" BorderColor="White" BorderWidth="2px" HeaderStyle-BackColor="#926c3f" HeaderStyle-Font-Bold="false" RowStyle-BorderColor="White" ID="GridView1" runat="server" DataSourceID="XmlDataSource1" AutoGenerateColumns="False" CssClass="auto-style100" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView1_SelectedIndexChanged" OnRowCancelingEdit="GridView1_SelectedIndexChanged" OnRowEditing="GridView1_SelectedIndexChanged" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText=" שם משחק" ItemStyle-Width="200px" >
<ItemTemplate >
<asp:Label ID="NameLabel" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameName").ToString())%>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="nameTB" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameName").ToString())%>'> </asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="קוד משחק" ItemStyle-Width="85px">
<ItemTemplate>
<asp:Label ID="codeLabel" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "gameCode").ToString())%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="הגדרות" ItemStyle-Width="70px">
<EditItemTemplate>
<asp:ImageButton ID="cancelImageButton" runat="server" ImageUrl="~/images/cancel.png" CommandName="cancel" OnClientClick="showWhoIsPublish" />
<asp:ImageButton ID="approveImageButton" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' runat="server" ImageUrl="~/images/approve.png" CommandName="approve" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="settingsImageButton" runat="server" CssClass="buttons" ImageUrl="~/images/אייקון הגדרות.png" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' CommandName="edit" OnClientClick="showWhoIsPublish" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="עריכה" ItemStyle-Width="70px" >
<ItemTemplate>
<asp:ImageButton ID="editImageButton" runat="server" CssClass="buttons" ImageUrl="~/images/אייקון עריכה.png" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' CommandName="editQ" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="מחיקה" ItemStyle-Width="70px">
<ItemTemplate>
<asp:ImageButton ID="deleteImageButton" CssClass="buttons" OnClick="doDelete_Click" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' runat="server" ImageUrl="~/images/אייקון מחיקה.png" CommandName="deleteRow" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" הגבלת זמן" ItemStyle-Width="90px" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownListT" AppendDataBoundItems="True" runat="server" >
<asp:ListItem> 10 שניות</asp:ListItem>
<asp:ListItem> 20 שניות</asp:ListItem>
<asp:ListItem> 30 שניות</asp:ListItem>
<asp:ListItem> 40 שניות</asp:ListItem>
<asp:ListItem> 50 שניות</asp:ListItem>
<asp:ListItem> 60 שניות</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate >
<asp:Label ID="Time" runat="server" Text='<%#Server.UrlDecode(XPathBinder.Eval(Container.DataItem, "time").ToString())%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="פרסום" ItemStyle-Width="60px">
<ItemTemplate>
<asp:CheckBox runat="server" ID="Checkbox1" CssClass="buttons1" theItemId='<%#XPathBinder.Eval(Container.DataItem, "#id")%>' AutoPostBack="True" OnCheckedChanged="PublishYesNo_CheckedChanged" ViewStateMode="Inherit" EnableViewState="True" Checked="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void GridView1_SelectedIndexChanged(object sender, GridViewCommandEventArgs e)
{
showWhoIsPublish();
ImageButton i = (ImageButton)e.CommandSource;
// אנו מושכים את האי די של הפריט באמצעות מאפיין לא שמור במערכת שהוספנו באופן ידני לכפתור-תמונה
string theId = i.Attributes["theItemId"];
Session["theId"] = theId;
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
switch (e.CommandName)
{
//אם נלחץ על כפתור מחיקה יקרא לפונקציה של מחיקה
case "deleteRow":
popOfDelete.Visible = true;
string deleteId = (string)Session["theId"];
string theGameNameDelete = Server.UrlDecode(xmlDoc.SelectSingleNode("//game[#id='" + (string)Session["theId"] + "']/gameName").InnerXml);
nameOfGameDelete.Text = "'" + theGameNameDelete + "' " + "?";
showWhoIsPublish();
break;
case "editQ":
string editId = (string)Session["theId"];
string theGameNameEdit = xmlDoc.SelectSingleNode("//game[#id='" + (string)Session["theId"] + "']/gameName").InnerXml;
Session["nameOfEdit"] = theGameNameEdit;
Response.Redirect("Default3.aspx");
break;
case "edit":
addNameTB.Text = "jg";
showWhoIsPublish();
break;
case "cancel":
GridView1.DataBind();
showWhoIsPublish();
break;
case "approve":
GridViewRow gvRow = (GridViewRow)(i.Parent.Parent);
string ApproveId = (string)Session["theId"];
int index = gvRow.RowIndex;
string myName = ((TextBox)GridView1.Rows[index].FindControl("nameTB")).Text;
string myValue = ((DropDownList)GridView1.Rows[index].FindControl("DropDownListT")).Text;
xmlDoc.SelectSingleNode("//game[#id='" + ApproveId + "']/gameName").InnerText = Server.UrlEncode(myName);
xmlDoc.SelectSingleNode("//game[#id='" + ApproveId + "']/time").InnerText = Server.UrlEncode(myValue);
XmlDataSource1.Save();
// יציאה ממצב של עריכה
GridView1.EditIndex = -1;
// ריענון הגריד ויו
GridView1.DataBind();
showWhoIsPublish();
break;
}
}
protected void showWhoIsPublish()
{
//סימון מה שמפורסם
XmlDocument xmlDoc = XmlDataSource1.GetXmlDocument();
XmlNodeList myListPublish = xmlDoc.SelectNodes("/games/user[#id='" + Session["id"] + "']/game/#isPublish");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkItem = (CheckBox)GridView1.Rows[i].FindControl("Checkbox1");
if (myListPublish.Item(i).InnerXml == "yes")
{
chkItem.Checked = true;
}
else
{
chkItem.Checked = false;
}
}
}

Make Gridview display checkboxes instead of 0s and 1s

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

How to select all checkboxes in just one particular column in GridView?

I have a GridView in which there are two columns of checkboxes i want to add two seperate "check all" text boxes at the top, "check all" above column A should check all the checkboxes in that column only. "check all" above column B should check all the columns in column B only. Also i am not able to apply groupvalidation. For every row only one of the two columns should get selected. I tried finding solution but when i click on check all at the top it checks all the checkboxes present in the gridview and also there is no group validation. Here is my Code..
HEAD:
<script type = "text/javascript">
function Check_Click(objRef) {
//Get the Row based on checkbox
var row = objRef.parentNode.parentNode;
if (objRef.checked) {
//If checked change color to Aqua
row.style.backgroundColor = "aqua";
}
else {
//If not checked change back to original color
if (row.rowIndex % 2 == 0) {
//Alternating Row Color
row.style.backgroundColor = "#C2D69B";
}
else {
row.style.backgroundColor = "white";
}
}
//Get the reference of GridView
var GridView = row.parentNode;
//Get all input elements in Gridview
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
//The First element is the Header Checkbox
var headerCheckBox = inputList[0];
//Based on all or none checkboxes
//are checked check/uncheck Header Checkbox
var checked = true;
if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
if (!inputList[i].checked) {
checked = false;
break;
}
}
}
headerCheckBox.checked = checked;
}
</script>
<script type = "text/javascript">
function checkAll(objRef) {
var GridView = objRef.parentNode.parentNode.parentNode;
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
//Get the Cell To find out ColumnIndex
var row = inputList[i].parentNode.parentNode;
if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
if (objRef.checked) {
//If the header checkbox is checked
//check all checkboxes
//and highlight all rows
row.style.backgroundColor = "aqua";
inputList[i].checked = true;
}
else {
//If the header checkbox is checked
//uncheck all checkboxes
//and change rowcolor back to original
if (row.rowIndex % 2 == 0) {
//Alternating Row Color
row.style.backgroundColor = "#C2D69B";
}
else {
row.style.backgroundColor = "white";
}
inputList[i].checked = false;
}
}
}
}
</script>
BODY:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="RollNo" HeaderText="RollNo" />
<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1">
</asp:CalendarExtender>
</EditItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><asp:CalendarExtender ID="CalendarExtender2"
runat="server" TargetControlID="TextBox2">
</asp:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Time" />
<asp:TemplateField HeaderText="Absent">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Text="Absent" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Present">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Text="Present"
onclick = "Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Ok i found solution to my problem. Although there is still one glitch.
Head:
<div runat="server">
<script type="text/javascript">
function SelectAll(id) {
//get reference of GridView control
var grid = document.getElementById("<%= GridView1.ClientID %>");
//variable to contain the cell of the grid
var cell;
if (grid.rows.length > 0) {
//loop starts from 1. rows[0] points to the header.
for (i = 1; i < grid.rows.length; i++) {
//get the reference of first column
cell = grid.rows[i].cells[4];
//loop according to the number of childNodes in the cell
for (j = 0; j < cell.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell.childNodes[j].type == "checkbox") {
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
function SelectAll1(id) {
//get reference of GridView control
var grid = document.getElementById("<%= GridView1.ClientID %>");
//variable to contain the cell of the grid
var cell;
if (grid.rows.length > 0) {
//loop starts from 1. rows[0] points to the header.
for (i = 1; i < grid.rows.length; i++) {
//get the reference of first column
cell = grid.rows[i].cells[3];
//loop according to the number of childNodes in the cell
for (j = 0; j < cell.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell.childNodes[j].type == "checkbox") {
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
</script>
<script type = "text/javascript">
function CheckBoxCheck(rb) {
var gv = document.getElementById("<%=GridView1.ClientID%>");
var row = rb.parentNode.parentNode;
var rbs = row.getElementsByTagName("input");
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "checkbox") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
</script>
</div>
Body:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="RollNo" HeaderText="RollNo" />
<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1">
</asp:CalendarExtender>
</EditItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><asp:CalendarExtender ID="CalendarExtender2"
runat="server" TargetControlID="TextBox2">
</asp:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Time" />
<asp:TemplateField HeaderText="Present">
<AlternatingItemTemplate>
<asp:CheckBox ID="cbSelectAll1" runat="server" onclick="CheckBoxCheck(this)" />
</AlternatingItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll1" runat="server" Text="All Absent"
onclick="CheckBoxCheck(this)" AutoPostBack="True" ValidationGroup="a" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbSelectAll1" runat="server" onclick="CheckBoxCheck(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" onclick="CheckBoxCheck(this)"/>
</AlternatingItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="All Present"
onclick="CheckBoxCheck(this)" AutoPostBack="True" ValidationGroup="a" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" onclick="CheckBoxCheck(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Find the checkbox control in header and add an attribute
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
((CheckBox)e.Row.FindControl("cbSelectAll1")).Attributes.Add("onclick", "javascript:SelectAll1('" + ((CheckBox)e.Row.FindControl("cbSelectAll1")).ClientID + "')");
}
}
The glitch is that user can still select both the "check all" and therefore both the columns get selected at the same time. Athough only one can be selected when not using select all check box.

Gridview Validation

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.

Categories

Resources