looping through gridview does not always work - c#

Not sure what is causing this I have tried a few suggestions none seem to help. I have debugged my application dozens of times and the problem never occur while debugging everything steps through just fine. But when I publish my application and allow people to use it is when the problem occurs and it is not for everyone just randomly decides that a checkbox is not checked and skips the whole process also on the front end I have a validation that requires at least one checkbox to checked before the button_click will fire so I know that they had to have one checked.
Gridview
<div id="divEventDetail">
<asp:GridView ID="grdEventDetail" runat="server" AutoGenerateColumns="False" DataKeyNames="EDID" Width="381px" OnRowDataBound="grdEventDetail_RowDataBound" GridLines="Horizontal">
<Columns>
<asp:TemplateField HeaderText="EventID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblEventID" runat="server" Text='<%# Eval("EDID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Register" ItemStyle-CssClass="template-center">
<ItemTemplate >
<asp:CheckBox ID="chkRegister" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Wait List" ItemStyle-CssClass="template-center">
<ItemTemplate>
<asp:CheckBox ID="chkWaitList" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
CodeBehind
protected void registerEvent()
{
foreach (GridViewRow row in grdEventDetail.Rows)
{
CheckBox chkR = row.FindControl("chkRegister") as CheckBox;
CheckBox chkW = row.FindControl("chkWaitList") as CheckBox;
if (chkR != null && chkW != null)// It is a datarow
{
GridViewRow Rowr = ((GridViewRow)chkR.Parent.Parent);
GridViewRow Roww = ((GridViewRow)chkW.Parent.Parent);
if ((chkR.Checked) || (chkW.Checked))
// if ((((CheckBox)row.FindControl("chkRegister")).Checked == true) || (((CheckBox)row.FindControl("chkWaitList")).Checked == true))
{
Label eventID = row.FindControl("lblEventID") as Label;
***Then i do my database stuff here

I believe the grdEventDetail GridView doesn't have CheckBoxes in each row. For example, HeaderRow and FooterRow probably don't have those CheckBoxes.
I would rewrite the code to eliminate any error:
protected void registerEvent()
{
foreach (GridViewRow row in grdEventDetail.Rows)
{
CheckBox chkR = row.FindControl("chkRegister") as CheckBox;
CheckBox chkW = row.FindControl("chkWaitList") as CheckBox;
if(chkR != null && chkW != null)// It is a datarow
{
GridViewRow Rowr = ((GridViewRow)chkR.Parent.Parent);
GridViewRow Roww = ((GridViewRow)chkW.Parent.Parent);
if ((chkR.Checked) || (chkW.Checked))
{
//Your code goes here
}
}
}
}

Related

get the value of each check marked check box inside rad grid in code behind

In my radgrid I am using check box to select the required values from the multiple options. In my code behind, I want to get the value of every checked rows. But my loop is not working.
Also I am not sure whether I am using the correct approach for the checkbox inside rad grid. Please suggest.
<telerik:RadGrid ID="rg_get_profession" runat="server"
PageSize="100"
AllowSorting="true"
Width="100%"
AllowPaging="True"
ShowGroupPanel="false"
AutoGenerateColumns="false"
GridLines="Both"
HeaderStyle-HorizontalAlign="Left" >
<MasterTableView AutoGenerateColumns="false" AllowFilteringByColumn="false" ShowFooter="false">
<Columns>
<telerik:GridTemplateColumn UniqueName="TempCol1" HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="p_id" Display="false" Visible="true" AutoPostBackOnFilter="false" CurrentFilterFunction="Contains" />
<telerik:GridBoundColumn DataField="p_name" HeaderText="Name" AutoPostBackOnFilter="false" CurrentFilterFunction="Contains" />
</Columns>
</MasterTableView>
</telerik:RadGrid>
What I want to do is to insert the "p_id" for each checked rows in the database. But my loop is not working. Please suggest how can I achieve this.
code behind >>
foreach (GridDataItem item in rg_get_profession.Items)
{
CheckBox chkbox = item.FindControl("TempCol1") as CheckBox;
if(chkbox != null && chkbox.Checked)
{
string id = item.Cells[1].Text;
}
}
While debugging the code, the execution does not go inside the if block though I checked multiple items in the rad grid check box.
I tried doing ::
foreach (GridDataItem item in rg_get_profession.MasterTableView.Items)
{
CheckBox chkbox = item.FindControl("CheckBox1") as CheckBox;
if (chkbox != null && chkbox.Checked)
{
string id_ = item.Cells[1].Text;
}
}
Now when I put check mark in the check boxes, my execution goes inside the loop if (chkbox != null && chkbox.Checked) but I can not access the value of p_id.
string id_ = item.Cells[1].Text; is not giving the value of p_id.
How can I access the value of p_id which are check marked? Please suggest.
I changed the item.Cells[1].Text; to item["p_id"].Text;.
Code snippet to get the value of the datafield ::
foreach (GridDataItem item in rg_get_profession.MasterTableView.Items)
{
CheckBox chkbox = item.FindControl("CheckBox1") as CheckBox;
if (chkbox != null && chkbox.Checked)
{
string id_ = item["p_id"].Text;
}
}
I can get the value of the p_id which are checked mark.

Adding a checkbox column to asp.net gridview

I have a couple questions when it pertains to adding a CheckBox column to gridview in asp.net and getting multiple values. First off I see everyone adding OnCheckedChanged="chkview_CheckedChanged" to their aspx page but when you click on the CheckBox to set its actions it does not open OnCheckedChanged="chkview_CheckedChanged". It opens SelectedIndexChanged event instead. What I am trying to do is when they select a CheckBox it adds the corresponding rows info to the TextBox. Here is what I am currently using to set the values. How can I use a selected CheckBox instead?
protected void dropGridView_SelectedIndexChanged1(object sender, EventArgs e)
{
GridViewRow row = dropdeadGridView.SelectedRow;
IDTextBox.Text = row.Cells[1].Text;
loadnumTextBox.Text = row.Cells[2].Text;
}
Once done with that how can you make it to where it will get every row that is checked instead of just one which is what is my current problem. I am looking for a way to select multiple rows and have a select button. I have done a lot of looking and can find nothing on it so I am trying to accomplish this with CheckBoxes instead. Any ideas how I can add this and get the multiple rows that can be selected. Thank you in advance.
Here is my edit* Posting asp code for CheckBox column:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="SelectCheckBox" runat="server" OnCheckedChanged="SelectCheckBox_OnCheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
First you have to set autopostback attribute to true :
<asp:CheckBox ID="SelectCheckBox" runat="server" AutoPostBack="true"
OnCheckedChanged="SelectCheckBox_OnCheckedChanged"/>
In your case, SelectedIndexChanged is sent by the gridview. For the checkbox event you have to use OnCheckedChanged event :
protected void SelectCheckBox_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chk = sender as CheckBox ;
if(chk.Checked)
{
GridViewRow row = (GridViewRow)chk.NamingContainer;
IDTextBox.Text = row.Cells[1].Text;
loadnumTextBox.Text = row.Cells[2].Text;
}
}
If you want to loop through all selected checkboxes :
var rows = dropdeadGridView.Rows;
int count = dropdeadGridView.Rows.Count;
for (int i = 0; i < count; i++)
{
bool isChecked = ((CheckBox)rows[i].FindControl("chkBox")).Checked;
if(isChecked)
{
//Do what you want
}
}
HTML Gridview example
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Class="table table-striped table-bordered" ShowHeaderWhenEmpty="true" HeaderStyle-HorizontalAlign="Center" RowStyle-HorizontalAlign="Center" HorizontalAlign="Center" Height="40px" Width="80%" EmptyDataText="No Stock in The Shop"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:CheckBox ID="chkAllSelect" runat="server" onclick="checkAll(this);" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chkSelect" onclick="Check_Click(this);EnableBTN(this);" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="SHOP_CODE" HeaderText="SHOP CODE" /> <asp:BoundField DataField="ITEM_CODE" HeaderText="ITEM CODE" /> <asp:BoundField DataField="ITEM_NAME" HeaderText="ITEM NAME" /> <asp:BoundField DataField="COLOR_CODE" HeaderText="COLOR CODE" /> <asp:BoundField DataField="COLOR_NAME" HeaderText="COLOR NAME" /> <asp:BoundField DataField="STOCK_NO" HeaderText="STOCK NUMBER" /> <asp:BoundField DataField="STOCK_IN_HAND" HeaderText="STOCK IN HAND" /> <asp:BoundField DataField="LOCATION_CD" HeaderText="LOCATION" /> <asp:TemplateField HeaderText="NO OF QUANTITY"> <ItemTemplate> <asp:TextBox CssClass="form-control" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');" Placeholder="Enter The Correct Qty" ID="ADJqty" runat="server" AutoCompleteType="Disabled" Text=""></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
Use this function check all the gridview check box
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 = "#e3f1ff";
inputList[i].checked = true;
$('#DummyBTNAUTHLeave').prop('disabled', false);
$('#DummyBTNRJTLeave').prop('disabled', false);
}
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 = "rgba(0,0,0,.05)";
}
else {
row.style.backgroundColor = "white";
}
inputList[i].checked = false;
$('#DummyBTNAUTHLeave').prop('disabled', true);
$('#DummyBTNRJTLeave').prop('disabled', true);
}
}
}
}
check the specifyed checkbox in gridview
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 = "#e3f1ff";
}
else {
//If not checked change back to original color
if (row.rowIndex % 2 == 0) {
//Alternating Row Color
row.style.backgroundColor = "rgba(0,0,0,.05)";
}
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;
}

Conditionally Hide Checkbox in row of Gridview

I'm having a ton of trouble and I've followed plenty of example codes from people with the same question. Basically I have a gridview and I have a column with checkboxes and another with a linkbutton. I want to hide/disable a checkbox in a row, if the databound linkbutton in the other column isn't null (field isn't empty). I've tried every way of doing this...(lb!=null), (lb.Text!=null) Also, I have tried finding the controls by Column Number...no luck
What am I doing wrong? (gridview functions normally other than the checkbox hiding feature)
I tried debugging and it seemed that it wasn't getting passed the first if statement (rowtype==...)
.cs:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("LinkButtonPO") as LinkButton;
if (lb.CommandArgument != null)
{
CheckBox cb = e.Row.FindControl("CbPO") as CheckBox;
if (cb != null)
cb.Visible = false;
}
}
}
.aspx
<asp:GridView ID="GridView1"
CssClass="Gridview" runat="server"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="Order_ID"
DataSourceID="OrderHistoryData"
HorizontalAlign="Center"
EmptyDataText="No Data to Display"
Width="785px"
AlternatingRowStyle-CssClass="alt" AllowPaging="True"
PagerStyle-CssClass="pager" GridLines="None" PageSize="20"
ShowHeaderWhenEmpty="True" OnRowDataBound="GridView1_RowDataBound">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonPO" runat="server" CommandArgument='<%# Bind("PO_ID") %>' OnClick="LinkButtonPO_Click" Text='<%# Bind("PO_Lit") %>'></asp:LinkButton>
</ItemTemplate>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="CbPO" runat="server" OnCheckedChanged="CbPO_CheckedChanged" Visible="true" />
</ItemTemplate>
</asp:TemplateField>
LinkButton.CommandArgument is implemented in this way(ILSpy on .NET 4):
public string CommandArgument
{
get
{
string text = (string)this.ViewState["CommandArgument"];
if (text != null)
{
return text;
}
return string.Empty;
}
set
{
this.ViewState["CommandArgument"] = value;
}
}
So as often in ASP.NET the property is never null but String.Empty.
So change
if (lb.CommandArgument != null)
cb.Visible = false;
to
cb.Visible = lb.CommandArgument.Length > 0;
I am using like this and works for me
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lb = e.Row.FindControl("LinkButtonPO") as LinkButton;
CheckBox cb = e.Row.FindControl("CbPO") as CheckBox;
if (cb != null)
{
cb.Visible = false;
}
}
}
You did not use Columns and Asp:TemplateField for Linkbutton So use that.

how to prevent disabled checkboxes of gridview from getting checked when select all checkbox is clicked?

I have used gridview in my aspx page.. In that i have a check box at each row including header..
By clicking the header checkbox it will check all the checkboxes including disabled checkboxes in gridview.. I need to avoid the disabled checkbox from getting checked
This is my gridview code:
<asp:GridView ID="CrowdRatingGrid" runat="server" AutoGenerateColumns="false" AllowPaging="true" PageSize="4" OnPageIndexChanging="CrowdRatingGrid_PageIndexChanging" ViewStateMode="Enabled">
<PagerSettings Mode="Numeric" PageButtonCount="4" />
<Columns>
<asp:TemplateField HeaderStyle-BackColor="#DBE2E2" HeaderStyle-Width="60px" HeaderStyle-HorizontalAlign="Center"
HeaderStyle-Height="62px">
<HeaderTemplate>
<asp:CheckBox ID="SelectAll" runat="server" onclick="SelectAll(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="CheckRow" CssClass="SelectRow" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my js code for selecting all checkbox:
function SelectAll(objRef) {
var GridView = objRef.parentNode.parentNode.parentNode;
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
var row = inputList[i].parentNode.parentNode;
if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
if (objRef.checked) {
inputList[i].checked = true;
}
else {
inputList[i].checked = false;
}
}
}
}
Please help in achieving this? What change should i make in js to achieve my requirement?
Change condition to
if (objRef.checked && !inputList[i].disabled) {
inputList[i].checked = true;
}
else {
inputList[i].checked = false;
}

Unable to delete multiple grid view records

I am trying to delete multiple grid view records. I tried as shown below.
public void btnDelete_Click(object sender, EventArgs e)
{
StringCollection orderNumberCollection = new StringCollection();
if (gridOrders.Rows.Count > 0)
{
foreach (GridViewRow gvrow in gridOrders.Rows)
{
if (gvrow.RowType == DataControlRowType.DataRow) {
CheckBox cbx = (CheckBox)gvrow.Cells[0].FindControl("chkdelete");
Label lblOrderNumner = (Label)gvrow.FindControl("labelOrderNumber");
Label lastName = (Label)gvrow.FindControl("LabelLastName");
if (cbx.Checked && lblOrderNumner != null)
{
orderNumberCollection.Add(lblOrderNumner.Text);
}
}
}
}
if (orderNumberCollection.Count > 0)
{
DeleteMultipleOrders(orderNumberCollection);
}
}
But always check box control showing "Checked = false". Why check box control always showing false even I checked some of the check boxes?
Here is my Grid view code:
<asp:TemplateField>
<HeaderTemplate>
<table><tr><td ><asp:CheckBox ID="chkAll" runat="server" /></td><td><asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" /></td></tr></table>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" Text='<%# Bind("OrderNumber") %>' Font-Bold="false" />
</ItemTemplate>
</asp:TemplateField>
I'm with Tim on this, it sounds like you are loading your gridview from within Page_Load, which is fine. but in your case you would need to make sure your gridview loading code looks like this:
if(!Page.IsPostBack)
{
//gridview loading code
}
this prevents your gridview from being reloaded (and losing which boxes are checked) when you click your delete button

Categories