ASP.NET 'CheckAllCB' checkbox header template does not work - c#

I am using visual studio 2005 c#, and doing server side coding.
I have a checkbox template in my gridview. I have tried to assign a CheckAllCB button outside the gridview, so that whenCheckAllCB is clicked, the list of checkboxes in the item template will be checked.
However, it does not work and I am not able to spot the mistake.
Below is my code for my CheckAllCB button:
protected void CheckAllCB_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)GridView1.HeaderRow.FindControl("CheckAll");
if (chk.Checked)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("UserSelector");
chkrow.Checked = true;
}
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkrow = (CheckBox)GridView1.Rows[i].FindControl("UserSelector");
chkrow.Checked = false;
}
}
}
(SOLVED)
Thus I tried using a checkbox checkchange in the header template. However, when the checkbox CheckAll in header template is check changed, nothing happens in the checkboxes in the itemtemplate.
Below is my code for CheckAllCB in header template
private void ToggleCheckState(bool checkState)
{
// Iterate through the Products.Rows property
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox cb = (CheckBox)row.FindControl("UserSelector");
if (cb != null)
cb.Checked = checkState;
}
}
protected void CheckAll_Click(object sender, EventArgs e)
{
ToggleCheckState(true);
}
protected void UncheckAll_Click(object sender, EventArgs e)
{
ToggleCheckState(false);
}
Anyone can help me identify the mistake I did in my method? Thank you
UserSelection item template:
CheckAllCB header template:
Added source code for GridView:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" ondatabound="gv_DataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CheckAllCB" runat="server" OnCheckedChanged="CheckAllCB_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="UserSelection" OnCheckedChanged="UserSelector_CheckedChanged" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

You could do it on the client side. Here's how I normally do it with jQuery:
<asp:CheckBox ID='checkAll' runat='server' />
<asp:CheckBox ID='cb1' CssClass='checky' runat='server' />
<asp:CheckBox ID='cb2' CssClass='checky' runat='server' />
<script type='text/javascript'>
$(function() {
$('#<%= checkAll.ClientID %>').click(function() {
$(".checky").prop("checked", $(this).prop("checked"));
});
});
</script>

The problem is that the checkbox is declared as UserSelection in the page, but you are looking for UserSelector in codebehind.
Also, the header is declared as CheckAllCB in the page, but you are looking for CheckAll in the codebehind.
You need to change one or the other so that the names match.

Related

How can I get access to the button from code behind

How can I get access to the button from code behind using id "btnAutocomplete"?
<asp:GridView DataKeyNames="AutocompleteSchoolChild_Child" Width="1500px" CssClass="table table-bordered" OnDataBound="GridAutocomplete_OnDataBound"
ID="GridAutocomplete" runat="server" AutoGenerateColumns="false" AllowPaging="true" DataSourceID="sqlAutocomplete" Visible="true" PageSize="10"
OnSelectedIndexChanged="GridAutocomplete_OnSelectedIndexChanged">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-width="80px">
<ItemTemplate runat="server">
<asp:Button CssClass="btn btn-default" runat="server" ID="btnAutocomplete" Text="Зачислить" CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
...
I assume that you want to change button text in currently selected row, so that you need to use FindControl with GridViewRow instance & cast it to a Button control:
protected void GridAutocomplete_OnSelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridAutocomplete.SelectedRow;
Button btnAutocomplete = (Button)row.FindControl("btnAutocomplete");
btnAutocomplete.Text = "Insert"; // example to use button property
}
If you want to change button text in all GridView rows, you can use foreach loop together with GridViewRow instances on the same event handler:
foreach (GridViewRow row in GridAutocomplete.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Button btnAutocomplete = (Button)row.FindControl("btnAutocomplete");
btnAutocomplete.Text = "Insert"; // example to use button text property
}
}
If you're not sure that FindControl cast works properly, change all direct casts to as operator & use null checking like this:
GridViewRow row = (sender as GridView).NamingContainer as GridViewRow;
Button btnAutocomplete = row.FindControl("btnAutocomplete") as Button;
if (btnAutocomplete != null)
{
btnAutocomplete.Text = "Insert"; // example to use button text property
}
NB: The goal here is getting GridViewRow instance first before accessing button control inside TemplateField, so that SelectedRow is a proper way to get currently selected row.
Why don't you simply use GetElementById javascript method
document.getElementById("btnAutocomplete").innherHTML("");
Or jQuery:
("#btnAutocomplete").val = "";
As you've asked how to use this, I suggest that you add the code below after your HTML or your aspx layout code which you wrote in your question.
<script type="text/javascript">
//this function runs when the webpage is loaded
$(document).ready(function ()
{
document.getElementById("btnAutocomplete").innherHTML("whatever you want here");
//OR
("#btnAutocomplete").attr("style","whatever style html you want here");
});
//OR declare a private function which you can call through a click event
function buttonchange()
{
("#btnAutocomplete").val = "whatever value you want to give it";
}
</script>
You can assign the call event of the private function to some html element, for example:
<button type="button" class="btn" onclick="buttonchange()">Button changer</button>
i think you can define OnRowCommand for your gridview and define command name for your button,see this:
<asp:GridView DataKeyNames="AutocompleteSchoolChild_Child" Width="1500px" CssClass="table table-bordered" OnDataBound="GridAutocomplete_OnDataBound"
ID="GridAutocomplete" runat="server" AutoGenerateColumns="false" AllowPaging="true" DataSourceID="sqlAutocomplete" Visible="true" PageSize="10"
OnSelectedIndexChanged="GridAutocomplete_OnSelectedIndexChanged"
OnRowCommand="GridAutocomplete_RowCommand">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-width="80px">
<ItemTemplate runat="server">
<asp:Button CssClass="btn btn-default" runat="server" ID="btnAutocomplete" Text="Зачислить" CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
and in code behind:
protected void grdSms_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "select")
{
//do something
}
}

How to fetch values from cells inside Grid View

I have used grid view in my ASP.NET application.
<asp:GridView ID="grdView" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Jurisdiction">
<ItemTemplate>
<asp:Label ID="lblJurisdiction" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="License Number">
<ItemTemplate>
<asp:TextBox ID="txtLicenseNumber" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
in cs file
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
for (int i = 0; i < grdView.Columns.Count; i++)
{
String cellText = row.Cells[i].Text;
}
}
}
Note that the above grid will be populated by data. Now I need to get data from already populated gridview. The above code is not working. Also I need to retrieve from labels, textboxes, checkboxes values inside grid. Please help !!!
You can use FindControl method to retrieve the control's data:-
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
CheckBox chkbox = row.FindControl("chkbox") as CheckBox;
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
..and so on
//Finally retrieve the data like your normal control
string labelText = lblJurisdiction.Text;
}
}
Use GridViewRow.FindControl method.
foreach (GridViewRow row in grdView.Rows)
{
// return you the check-box control from current row
var chkbox = row.FindControl("chkbox");
}
Check whether the row type is DataControlRowType.DataRow.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in grdView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < grdView.Columns.Count; i++)
{
String cellText = row.Cells[i].Text;
}
}
}
}
To get the TextBox, CheckBox value from the grid use this,
string TextBoxvalue = ((TextBox)GridViewID.Rows[i].FindControl("TextBoxName")).Text;
string CheckBoxvalue = ((CheckBox)GridViewID.Rows[i].FindControl("CheckBoxName")).Text;
In your code .cs file, you are missing to check only for datarow. As it will check all 3 places:-
1. Header
2. Body
3. Footer
Might any one place, any exception can occur.
Please add one more if condtion just after the for loop, as below.
if (row.RowType == DataControlRowType.DataRow)
{
Hope this post will help's you :).
Use
cells[i].EditedFormatedValue

Gridview Checkbox Update User on a new page

I am trying to update a user in a different page with textboxes. But what I'm trying to do is select the user based on a Gridview.
So on the first page You see a gridview with a user list and checkboxes. You select a user with a check box and then hit the Edit User button. Then it goes to a new page which allows you to edit the user in textboxes but populates the data because of the ID or another unique column. How would I do this??
Here is the code I have so far:
protected void Button2_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox CheckBox1 = (CheckBox)gvrow.FindControl("chkSelect");
if (CheckBox1.Checked)
{
//Go to new page to edit user
}
else
{
//Do nothing if not checked
}
}
}
I assume that your checkbox is inside a <asp:TemplateField>.
So, in a <asp:TemplateField> you could add a <asp:HiddenField /> to store the ID of the user. Then you can get the ID by getting the value of the <asp:HiddenField />
ASPX markup:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="hfdUserID" runat="server" Value='<%#Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void Button2_Click(object sender, EventArgs e)
{
int userid = 0;
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox CheckBox1 = (CheckBox)gvrow.FindControl("chkSelect");
if (CheckBox1.Checked)
{
userid = Convert.ToInt32(((HiddenField)gvrow.FindControl("hfdUserID")).Value);
Response.Redirect("useredit.aspx?id=" + userid.ToString());
}
}
}
Edit: To get the user ID to the new page you can use the following and then use it accordingly
int userid = Convert.ToInt32(Request.QueryString["id"]);

How to delete a row without using OnRowDeleted/OnRowDeleting in gridview

Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow gvrow = lb.NamingContainer as GridViewRow;
gvsize.DeleteRow(gvrow.RowIndex);
}
GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView >
There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??
As stated in How to delete row from gridview?
You are deleting the row from the gridview but you are then going and
calling databind again which is just refreshing the gridview to the
same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
and remove it from the gridview without redatabinding.
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
//followed by your code
}
}
Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
OnClientClick="return confirm('Are you sure want to delete the current record ?')">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower().Equals("deletenotice"))
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
NoticeBoard notice = new NoticeBoard();
HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record
auditTrail.Action = DBAction.Delete;
Service simplyHRClient = new Service();
MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
if (messageClass.IsSuccess)
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "success-message";
if (messageClass.RecordId != -1)
lblCust.Value = messageClass.RecordId.ToString();
}
else
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "fail-message";
}
//Bind Again grid
GetAllNoticeBoard();
}
}
Hope it helps you

Variables lost on postback in asp.net

I have a gridview with some data and I want to add a checkbox column which can choose multiple rows. By clicking on it I want to save an primary key of row and change css class of row.
Using this article(step 2) I created itemtemplate,added there a checkbox(specifying ID as TransactionSelector), and add a checkedChange() to it. There I only change a css class of row and add a row index to arraylist. But when I click button with event which show this list, it has no items.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="TransactionSelector" runat="server"
oncheckedchanged="TransactionSelector_CheckedChanged" AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="iTransactionsId" HeaderText="iTransactionsId"
SortExpression="iTransactionsId" />
<asp:BoundField DataField="mAmount" HeaderText="mAmount"
SortExpression="mAmount" />
<asp:BoundField DataField="vchTransactionType" HeaderText="vchTransactionType"
SortExpression="vchTransactionType" />
<asp:BoundField DataField="dtDate" HeaderText="dtDate"
SortExpression="dtDate" />
<asp:BoundField DataField="cStatus" HeaderText="cStatus"
SortExpression="cStatus" />
<asp:BoundField DataField="test123" HeaderText="test123"
SortExpression="test123" />
</Columns>
<RowStyle CssClass="unselectedRow" />
</asp:GridView>
</asp:Panel>
<asp:Panel ID="InfoPanel" runat="server" CssClass="infoPanel">
<asp:Button ID="ShowSelected" runat="server" Text="Button"
onclick="ShowSelected_Click" />
<asp:Label ID="InfoLabel" runat="server"></asp:Label>
</asp:Panel>
C Sharp code:
public partial class WebForm1 : System.Web.UI.Page
{
ArrayList indices = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
protected void TransactionSelector_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
// row.CssClass = (cb.Checked) ? "selectedRow" : "unselectedRow";
if (cb.Checked)
{
row.CssClass = "selectedRow";
indices.Add(row.RowIndex);
}
else
{
row.CssClass = "unselectedRow";
indices.Remove(row.RowIndex);
}
}
protected void ShowSelected_Click(object sender, EventArgs e)
{
InfoLabel.Text = "";
foreach (int i in indices)
{
InfoLabel.Text += i.ToString() + "<br>";
}
}
}
}
You have to persist variable in postback using ViewState. Also its better if you use List<T> generic implementation rather than ArrayList
ViewState["Indices"] = indices;
And to recover it back
indices = ViewState["Indices"] as ArrayList;
As Habib said, you could use ViewState. You could also use ControlState instead, as shown here. If your code is in a custom control or user control, you may also need to override OnInit to
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}
Please feel free to respond with feedback. I'm new at posting answers.

Categories

Resources