Hide Gridview Using Javascript - c#

I Have some Problem in Hiding Rows of Gridview Using Javascript...
My Js Function is
<script type="text/javascript">
function HideRows(Gdview) {
rows = document.getElementById(Gdview).rows;
for (var i = 0; i < rows.length; i++) {
if (rows[i].cells[0].type == "checkbox") {
if (rows[i].cells[0].childNodes[0].checked) {
rows[i].style.display = "none";
}
}
}
}
</script>
I Have a Gridview ID="Gdview" Which has 5 Columns and Every Column has a checkbox with id="Chk" and i placed a Button after the Gridview(Button id="Btn") i wannt to hide the Selected rows using checkboxes..i tried the following code behind..but it is not working..what wud be the problem?? IS this Wrong Way????
protected void Btn_Click1(object sender, EventArgs e)
{
Btn.Attributes.Add("onclick", "HideRows('" + Gdview + "')");
}
2ND Question Likewise same as first one:
Here i am trying to select and unselect all checkboxes in gridview using respective link buttons...See my markup and JS:
<script type="text/javascript">
function SelectAll(b) {
var grid = document.getElementById("<%= Gdview.ClientID %>");
var cell;
if (grid.rows.length > 0) {
for (var i = 0; i < grid.rows.length; i++) {
cell = grid.rows[i].cells[0];
if (cell.childNodes[0].type == "checkbox")
cell.childNodes[0].checked = b;
}
}
}
</script>
<asp:GridView ID="Gdview" runat="server" AutoGenerateColumns="False"
onrowdatabound="Gdview_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="SNO" DataField="SerialNo" />
<asp:BoundField HeaderText="Organization" DataField="Organization" />
<asp:BoundField DataField="Origin" HeaderText="Origin"/>
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="Established" HeaderText="Established"/>
<asp:TemplateField>
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinkButton ID="lnkChekall" runat="server" Text="Chekall"></asp:LinkButton>
<asp:LinkButton ID="lnkUncheck" runat="server" Text="UnCheckAll"></asp:LinkButton>
and i added Rowdatabound event in codebehind:
protected void Gdview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lnkChekall.Attributes.Add("onclick","javascript:SelectAll('" +"true" +"')");
lnkUncheck.Attributes.Add("onclick", "javascript:SelectAll('" + "false" +"')");
}
}
it is not working guys plz help me in my problems with the Javascripts...

EDIT 3
In your second question, I can see there are few problems:
You should not add attribute in RowDataBound. It would add the
attribute for each row instead of only once.
Your javascript is wrong.
You should pass boolean true/false to javascript function, not
string.
To make it work, Add the attributes at Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//PopulateGridView
PopulateGrid();
}
lnkChekall.Attributes.Add("onclick", "javascript:SelectAll(true)");
lnkUncheck.Attributes.Add("onclick", "javascript:SelectAll(false )");
}
And change your javascript to this:
<script type="text/javascript">
function SelectAll(b) {
var grid = document.getElementById("<%= Gdview.ClientID %>");
var cell;
if (grid.rows.length > 0) {
for (var i = 0; i < grid.rows.length; i++) {
cell = grid.rows[i].getElementsByTagName("input");
if (cell.length > 0) {
cell[0].checked = b;
}
}
}
}
</script>
You are doing it wrong way! There's no need to call JS from code behind. Just add style to make the row invisible. Here's how I would do it:
In the markup I have my GridView with five check boxes and one row number (Just to populate the Gridview with data). I also have a button :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="CheckBox 1">
<ItemTemplate>
<asp:CheckBox ID="chk1" Text="CheckBox 1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 2">
<ItemTemplate>
<asp:CheckBox ID="chk2" Text="CheckBox 2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 3">
<ItemTemplate>
<asp:CheckBox ID="chk3" Text="CheckBox 3" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 4">
<ItemTemplate>
<asp:CheckBox ID="chk4" Text="CheckBox 4" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 5">
<ItemTemplate>
<asp:CheckBox ID="chk5" Text="CheckBox 5" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row">
<ItemTemplate>
<%#Container.DataItem %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Btn" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Now in the code I am populating the GridView with test data. In the button's click event I am looping through all rows of GridView and finding the first CheckBox. If it is checked, I am hiding the row:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Test Data
var lst = new List<string>() { "Row 1", "Row 2", "Row 3" };
GridView1.DataSource = lst;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("chk1") as CheckBox;
if (chk != null && chk.Checked)
{
row.Attributes.Add("style", "display:none");
}
}
}
EDIT : If you want to use javascript, still there's no need to assign it from code behind. Add an input to the markup to call js HideRows() function:
<asp:Button ID="Btn" runat="server" Text="Button" OnClick="Button1_Click" />
And the function in the page should look like this:
<script type="text/javascript" >
function HideRows(Gdview) {
var rows = document.getElementById(Gdview).rows;
for( var i=0; i < rows.length; i++ ) {
var inputs = rows[i].getElementsByTagName("input");
if (inputs.length > 0 && inputs[0].checked) {
rows[i].style.display = "none";
}
}
}
</script>
Here's the screenshot before and after clicking the button:
You can download my test project here.
EDIT 2 : If you need to call the function from code behind, just do this:
protected void Button1_Click(object sender, EventArgs e)
{
//Your other code goes here
//
Page.ClientScript.RegisterStartupScript(GetType(), "HideRows", "HideRows('" + GridView1.ClientID + "');", true);
}

client Id of server control is different from the Id you assigned, so try:
document.getElementById("<%= Gdview .ClientID %>")
complete code:
//dont pass as parameter
function HideRows() {
rows = document.getElementById("<%= Gdview.ClientID %>").rows;
for (var i = 0; i < rows.length; i++) {
if (rows[i].cells[0].type == "checkbox") {
if (rows[i].cells[0].childNodes[0].checked) {
rows[i].style.display = "none";
}
}
}
}

Related

Hide/show gridview column based on role

Want to be able to set an "Edit" linkbutton to visible=false unless the user has a role of "Editor".
Been poking around stackoverflow and elsewhere and so far have not been able to get this to work.
Gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Questions Awaiting Review" AllowSorting="True" PagerSettings-Mode="NumericFirstLast"
OnPageIndexChanging="GridView1_PageIndexChanging" CaptionAlign="Top" EmptyDataText="No Questions Pending Review."
PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large" DataKeyNames="QuestionID"
OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc"
OnPreRender="GridView1_OnPreRender">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="60" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="viewQuestion">View Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Have changed the code behind to use OnPreRender for the gridview, which if the value is hardcoded hides the column. However when I try to retrieve the is in role of editor then the value does not seem to be evaluating correctly. Always returns false even when the user has a role of Editor.
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
if (Roles.IsUserInRole("Editor"))
{
// Enter correct column index.
GridView1.Columns[4].Visible = true;
}
else
{
GridView1.Columns[4].Visible = false;
}
}
Hoping I'm missing something simple, new to asp.net so not unlikely.
Hide last column.
this.GridView1.Columns[this.GridView1.Columns.Count - 1].Visible = Roles.IsUserInRole("Editor");
You want to show/hide an entire column instead of LinkButton control. Otherwise, unauthorized user will always see a column with blank cells which is odd.
The following example will hide an entire column.
Screen Shot (Authorize vs Unauthorized)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1"
runat="server"
DataKeyNames="QuestionID"
OnPreRender="GridView1_OnPreRender"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>'
runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
public class Question
{
public int QuestionID { get; set; }
public string KeyObjective { get; set; }
}
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = new List<Question>
{
new Question {QuestionID = 1, KeyObjective = "One"},
new Question {QuestionID = 2, KeyObjective = "Two"},
new Question {QuestionID = 3, KeyObjective = "Three"},
};
GridView1.DataBind();
}
}
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
bool isEditor = true; // Business logic here
if (isEditor)
{
// Enter correct column index.
GridView1.Columns[2].Visible = false;
}
}
}
Use the LinkButton like this, with the Visibility property set from a function in code behind.
<asp:LinkButton ID="Edit" Visible='<%# ShowEditBasedOnRole() %>' CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
And then in code behind the function that returns a bool
public bool ShowEditBasedOnRole()
{
if (Roles.IsUserInRole("Editor"))
{
return true;
}
else
{
return false;
}
}
One quick modification instead of accessing the column by index. it can be accessed using header text which would not affect the code even if new column is inserted before the accessed column in future the code snippet
protected void grdResults_OnPreRender(object sender, EventArgs e)
{
TemplateField FieldToAccess= grdResults.Columns.OfType<TemplateField>
().Where(f => f.HeaderText ==
"ValidityDate").FirstOrDefault();
if (role)
FieldToAccess.Visible = false;
}

Display nested gridview

I have a nested GridView with 4 levels,
when i click in "+" to show child GridView i make request to database to download data of current row, every thing work well for me, the only problem i have is in design, all the child GridView display in column of its parent GridView
this is how it looks:
Parent GridView
First Child gridView
here is my aspx code:
<asp:UpdatePanel ID="upNestedGridView" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvCostCenters" runat="server" ....>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowAccountingPlan" runat="server" OnClick="Show_Hide_AccountingPlansGrid" .../>
<asp:Panel ID="pnlAccountingPlan" runat="server" Visible="false" Style="position: relative">
<asp:GridView ID="gvAccountingPlans" runat="server" AutoGenerateColumns="false"....">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowPrograms" runat="server" OnClick="Show_Hide_ProgramsGrid" .../>
<asp:Panel ID="pnlPrograms" runat="server" Visible="false" Style="position: relative">
<asp:GridView ID="gvPrograms" runat="server" AutoGenerateColumns="false" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowProjects" runat="server" OnClick="Show_Hide_ProjectsGrid" ..../>
<asp:Panel ID="pnlProjects" runat="server" Visible="false" Style="position: relative">
<asp:GridView ID="gvProject" runat="server" ....>
.....
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Label" HeaderText="البند " ItemStyle-HorizontalAlign="Right" />
....
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="NumAccountingPlan" HeaderText="الخطة المحاسبية " ItemStyle-HorizontalAlign="Right" />
...
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
...
<asp:BoundField DataField="OperatingExpenses" HeaderText="المصروفات التشغيلية" DataFormatString="{0:#,##0.00;(#,##0.00);0}" />
</Columns>
</asp:GridView>
my jquery code:
<script type="text/javascript">
$(function () {
$("[src*=minus]").each(function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>");
$(this).next().remove()
});
});
</script>
My code C#:
protected void Show_Hide_AccountingPlansGrid(object sender, EventArgs e)
{
try
{
ServiceClass service = new ServiceClass();
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
_budget = service.GetBudgetById(int.Parse(hfIdBudget.Value));
row.FindControl("pnlAccountingPlan").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "/Content/img/minus.gif";
string idCostCenter = gvCostCenters.DataKeys[row.RowIndex].Value.ToString();
GridView gvAccountingPlans = row.FindControl("gvAccountingPlans") as GridView;
//gvAccountingPlans.ToolTip = costCenterId;
gvAccountingPlans.DataSource = AccountingPlanData(int.Parse(hfIdUser.Value), int.Parse(hfIdBudget.Value), int.Parse(idCostCenter));
gvAccountingPlans.DataBind();
}
else
{
row.FindControl("pnlAccountingPlan").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "/Content/img/plus.gif";
}
}
catch (Exception ex) { GlobalHelpers.Trace(ex); }
}
I notice that when i delete the UpdatePanel the first child GridView display well, but the others no.
How can i do to display all childs GridView well?
I'm sorry for my bad english
Code asp:
<asp:UpdatePanel ID="upNestedGridView" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvCostCenters" runat="server" AutoGenerateColumns="false" ....>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowAccountingPlan" runat="server" OnClick="Show_Hide_AccountingPlansGrid" ImageUrl="/Content/img/plus.gif" CommandArgument="Show" />
</ItemTemplate>
</asp:TemplateField>
....
<asp:TemplateField>
<ItemTemplate>
<tr visible="false" runat="server" id="trAccountingPlan">
<td visible="false" runat="server" id="tdAccountingPlan2"></td>
<td colspan="999" visible="false" runat="server" id="tdAccountingPlan">
<asp:GridView ID="gvAccountingPlans" runat="server" ....>
<Columns>
.....
</Columns>
</asp:GridView>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
Code C#:
protected void Show_Hide_AccountingPlansGrid(object sender, EventArgs e)
{
try
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
...
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "/Content/img/minus.gif";
row.FindControl("trAccountingPlan").Visible = true;
HtmlTableCell tdAccountingPlan = (HtmlTableCell)row.FindControl("tdAccountingPlan");
HtmlTableCell tdAccountingPlan2 = (HtmlTableCell)row.FindControl("tdAccountingPlan2");
tdAccountingPlan2.Visible = true;
tdAccountingPlan.Visible = true;
...
}
else
{
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "/Content/img/plus.gif";
row.FindControl("trAccountingPlan").Visible = false;
HtmlTableCell tdAccountingPlan = (HtmlTableCell)row.FindControl("tdAccountingPlan");
HtmlTableCell tdAccountingPlan2 = (HtmlTableCell)row.FindControl("tdAccountingPlan2");
tdAccountingPlan2.Visible = false;
tdAccountingPlan.Visible = false;
}
}
catch (Exception ex) { GlobalHelpers.Trace(ex); }
}

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.

Changing button text of gridview

I have a grid view which contains a button in a template field. I want to change the button text when the button click event is completed. Can somebody send me a sample code.
Thanks in advance
Here is a sample bit of code using the RowCommand() of the GridView.
ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl1" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND" Text="My Text!" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lst = new List<string>() { "asd", "xxx" };
GridView1.DataSource = lst;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MYCOMMAND")
{
Button Button1 = (Button)e.CommandSource;
if (Button1 != null)
Button1.Text = "changed text..";
}
}

.NET UpdatePanel and FaceBook / Twitter Buttons

I have an UpdatePanel which has a gridview inside it. On each of the gridviewrows, within the gridview, I have a Twitter and FaceBook button.
The gridview renders fine with the buttons on page load, however, once a partial postback is done on the updatepanel the Twitter and FaceBook buttons do not render.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- search controls.... -->
<asp:ImageButton ID="btnSearch" ImageUrl="~/img/button-search.gif" runat="server" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True"
BorderStyle="None" Font-Size="Small" GridLines="None" AllowPaging="True" ShowFooter="True"
Width="100%" OnPageIndexChanging="GridView1_PageIndexChanging">
<RowStyle CssClass="row1" />
<AlternatingRowStyle CssClass="row2" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Literal ID="ltlTwitter" runat="server" Text='<%# GetTwitterURL(Eval("ID"), Eval("SomeText")) %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal ID="ltlFacebook" runat="server" Text='<%# GetFacebookURL(Eval("ID")) %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" Visible="False" />
</Columns>
<EmptyDataTemplate>
<strong>There are no offers for this search criteria.</strong>
</EmptyDataTemplate>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSearch" />
</Triggers>
</asp:UpdatePanel>
Relevant C#:
public static string GetTwitterURL(object ID, object text)
{
...
StringBuilder sb = new StringBuilder();
sb.Append("<div>");
sb.Append("<a href=\"http://twitter.com/share\" " +
"class=\"twitter-share-button\" ");
sb.AppendFormat("data-url=\"{0}?ID={1}\" ", obj.Property, oID.ToString());
sb.Append("data-via=\"xxx\" ");
sb.AppendFormat("data-text=\"{0}\"", xxx);
sb.Append("data-count=\"none\">Tweet</a>");
sb.Append("</div>");
return sb.ToString();
}
public static string GetFacebookURL(object OfferID)
{
...
return string.Format("<fb:like href=\"{0}?ID={1}\" " +
"send=\"false\" layout=\"button_count\" show_faces=\"false\" " +
"action=\"like\" font=\"tahoma\"></fb:like>", obj.Property, someInt);
}
Also, the page in question is a child page of a master page.
Here is the additional code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindOffersGrid(true);
}
}
public List<Offer> CurrentOffersDataSet
{
get
{
object o = ViewState["CurrentOfferDataSet"];
return (o == null ? new List<Offer>() : (List<Offer>)o);
}
set
{
ViewState["CurrentOfferDataSet"] = value;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = this.CurrentOffersDataSet;
GridView1.DataBind();
}
private void BindOffersGrid(bool ApplyRandomSort)
{
List<Offer> lstOffers = Offers.GetAllBySearchCriteria(
Convert.ToInt32(ddlOfferCounty.SelectedValue),
Convert.ToInt32(ddlOfferTypes.SelectedValue),
Convert.ToDateTime(ddlOfferDate.SelectedValue), -1, true);
...
//Some filtering of the dataset with Linq
...
GridView1.DataSourceID = string.Empty;
this.CurrentOffersDataSet = lstFilteredOffers.
OrderByDescending(a => a.IsExclusive).
ThenBy(a => Guid.NewGuid()).
ToList();
GridView1.DataSource = this.CurrentOffersDataSet;
GridView1.DataBind();
}
Ok, I added the following code at the very end of my child page and now the Twitter and FaceBook like button are appearing after partial postbacks.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
var _panels, _count;
function pageLoaded(sender, args) {
if (_panels != undefined && _panels.length > 0) {
for (i = 0; i < _panels.length; i++)
_panels[i].dispose();
}
var panels = args.get_panelsUpdated();
if (panels.length > 0) {
updateFbLike();
}
}
function updateFbLike() {
$.getScript("http://platform.twitter.com/widgets.js");
FB.XFBML.parse();
}
</script>

Categories

Resources