Reference specific checkbox in gridview - c#

I have a GridView which show data retrived from database. I've made TemplateField (CheckBox) to GridView with this code:
<asp:GridView ID="dbRecordsContent" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="dbRecordsContent_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="myCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="title" HeaderText="title" SortExpression="title" />
<asp:BoundField DataField="url" HeaderText="url" SortExpression="url" />
<asp:BoundField DataField="category" HeaderText="category" SortExpression="category" />
<asp:BoundField DataField="isChecked" HeaderText="isChecked" SortExpression="isChecked" />
</Columns>
</asp:GridView>
My grid view looks like this:
My question is: How do I know which checkbox ID is checked? For example:
I want to delete 2nd row when I press "Delete" button. Of course I will check second Checkbox, but how do I know which record to delete? How to reference second checkbox in a code?

In your delete button's click event handler you need to loop through all the rows in the grid and if a check box is checked, then you need to perform your delete logic, like this:
protected void DeleteButton_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in dbRecordsContent.Rows)
{
// Only look for check boxes in data rows, ignoring header
// and footer rows
if (row.RowType == DataControlRowType.DataRow)
{
if (((CheckBox)row.FindControl("myCheckBox")).Checked)
{
// Do delete logic here
}
}
}
}
UPDATE:
To get the row number use the GridViewRow.RowIndex property, like this:
int rowNumber = row.RowIndex;
Read GridViewRow.RowIndex Property for more information.

try this,
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="myCheckBox" runat="server" AutoPostBack="true"
oncheckedchanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
code side,
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox cb1 = (CheckBox)Gridview.Rows[index].FindControl("myCheckBox");
string checkboxstatus;
if (cb1.Checked)
{
//write your code
}
else
{
//write your code
}
}

Related

Call checkbox in C# backend

I have one checkbox with ID=checkbox1 in Asp.net gridview. I want to use checkbox1 in if else condition in backend C# code.My problem is I am not getting how to call checkbox1 as it is not showing in the backend.
Thanks in advance.
My code is
if (txtsender.Text != String.Empty && checkbox1.checked==true)
{
chklist();
}
One view to access your checkbox inside Gridview is to loop on grid view rows and find your checkbox. Code example given below to access gridview checkbox in button click event
Aspx code
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBox" runat="server" AutoPostBack="true" Text="T1" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="Submit" />
Aspx.cs Code
protected void btn_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gv1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox c = (CheckBox)row.FindControl("chkBox");
if (c.Checked)
{
}
}
}
}

Can't bind checkboxes in Gridview

I have a GridView that displays a list and the user can select a checkbox for each item.
So for example I check the second row. I can see in the database that the check value next to this description has updated to 1:
But when I go back into the GridView, all the checkboxes are blank again.
Code for GridView:
<asp:GridView style="width:75%"
ID="gvCVRTDetails"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvCVRTDetails_RowDataBound"
DataKeyField="ID"
AutoGenerateColumns="false"
allowpaging="false"
AlternatingRowStyle-BackColor="#EEEEEE">
<HeaderStyle CssClass="tblResultsHeader" />
<Columns>
<asp:BoundField DataField="ChecklistID" HeaderText="ID" ></asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="Checklist Items"></asp:BoundField>
<asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkChecked" runat="server" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void gvCVRTDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lookupCVRT work = (lookupCVRT)e.Row.DataItem;
GridView gv = sender as GridView;
e.Row.Attributes.Add("ID", "gvCVRTDetails_" + work.ID);
e.Row.Cells[0].Attributes.Add("onclick", "event.stopPropagation();");
CheckBox chkChecked = e.Row.FindControl("chkChecked") as CheckBox;
if(work.Checked)
{
chkChecked.Checked = true;
}
}
}
I tried setting chkChecked.Checked = true; if there is a value for the Checked field in the database but that didn't work. How do I get the checkboxes to show as ticked if the value in the database is equal to 1?
Binding the Grid:
protected void gridviewParent_SelectedIndexChanged(object sender, EventArgs e)
{
List<lookupCVRT> workDetails = lookupCVRT.GetChecklistItemsByChecklistID(Company.Current.CompanyID, ParentID.ToString(), gvCVRT.SelectedDataKey.Value.ToString());
gvCVRTDetails.DataSource = workDetails;
gvCVRTDetails.DataBind();
FireJavascriptCallback("setArgAndPostBack ();");
}
You should bind the checkbox to the property that you read from db, something like:
<asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkChecked" Checked='<%# Bind("YourCheckPropertyFromModel") %>'runat="server" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>

asp gridview with checkbox and select

I am trying to develop an asp c# gridview that has select so that I can display additional details of the record. I also need a check box to allow the user the check the row for further processing. I can achieve each separately but not together. Is it even possible?
Of course it is possible.
For the column of check boxes, use TemplateField column, https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield%28v=vs.110%29.aspx
In data grid, aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" runat="server" />
</ItemTemplate>
</asp:TemplateField>
In code behind:
protected void ButtonProcess_Click(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBoxProcess");
if (chk != null)
{
if (chk.Checked)
{
// This record should be processed
}
}
}
}
The GridView has build in row select functionality, you can enable it by setting AutoGenerateSelectButton property to true:
<asp:GridView ... AutoGenerateSelectButton="true" />
However, it is more user friendly to select the row when user clicks on it (rather than clicking on the link).
To do this, you need to attach a bit of java-script to the row:
void GridView1_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
e.Row.Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(sender, "Select$" + e.Row.RowIndex.ToString())
}
Here is also, much better explained solution for row click select:
https://stackoverflow.com/a/6250846/461810
You can use template fields and just add the controls into them.
<Columns>
<asp:TemplateField>
<ItemTemplate>
<select />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<checkbox />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="SelectChk" OnCheckedChanged="chk_Click1" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
And in the CS code:
protected void chk_Click1(object sender, EventArgs e)
{
CheckBox MChk = sender as CheckBox;
GridViewRow MyGridR = MChk.NamingContainer as GridViewRow;
GridView1.SelectRow(MyGridR.RowIndex);
}

Asp GridView select a row then fire event

Here is the scenario ..
I have a GridView with columns ID, Name, and Type. Name is click enabled and will redirect to other page. The entire row can be selected, and using jQuery I changed its background so it will be recognized as selected row.
The reason it must be selected is because a link, for example Delete is present at the page. When Delete is clicked, it should delete the selected row but when there is no selected row, it should do nothing.
Here is my code:
<asp:LinkButton ID="btnDelete" runat="server">Delete</asp:LinkButton>
<asp:GridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound" OnRowCommand="gridView_Command" AutoGenerateColumns="false" >
<columns>
<asp:BoundField DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lb1" runat="server" Text='<%# Eval("Name") %>' CommandName="NameButton" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Type" />
</columns>
</asp:GridView>
public void gridView_Command(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "NameButton")
{
var id = e.CommandArgument;
// redirect to edit page //
}
}
I am using jQuery to indicate that a row is selected.
I already have the code for the Delete event method but my problem is how can I tell the compiler that a row is currently selected upon clicked of Delete?
I am thinking of using a hidden field, and on jQuery, I will set the value of the hidden field to the ID of the row that is selected. However, I still don't have the idea on how to do it.
It is pretty straight. You can store the SelectedIndex in a hidden field and find the GridViewRow by the index.
Add a hidden field in the markup and also attach an event method to the Link button:
<asp:LinkButton ID="btnDelete" OnClick="btnDelete_Click" runat="server">Delete</asp:LinkButton>
<asp:HiddenField ID="hdnIndex" runat="server" />
<asp:GridView ID="gridView" runat="server" OnRowDataBound="gridView_RowDataBound"
OnRowCommand="gridView_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ID" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lb1" runat="server" Text='<%# Eval("Name") %>' CommandName="NameButton" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Type" />
</Columns>
</asp:GridView>
In the GridView RowDataBound add an attribute to execute javascript to save index in hidden field:
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript: getElementById('" + hdnIndex.ClientID + "').value='" + e.Row.RowIndex + "';");
}
}
And LinkButton's click event do like this:
protected void btnDelete_Click(object sender, EventArgs e)
{
int index = 0;
int id = 0;
if (int.TryParse(hdnIndex.Value, out index))
{
GridViewRow gvr = gridView.Rows[index];
if (gvr != null && int.TryParse(gvr.Cells[0].Text, out id) )
{
// id is available here
// do wahtever you want with the id
// even you can delete the record from db by id
}
}
}
I guess command-argument is what you are searching for...Check this link
You just need to pass the Id using command argument from front-end to the code file and from there you can delete it easily.

DataKeyValues are null in gridview

Here is my gridview and the event that fires when a user clicks on the edit button within the row. for some reason my datakey value is crashing the program saying it is null. im not sure why. the DataKeyNames in the gridview is exactly what I want it to be, formID. this is correct because the last column in the gridview, as you can see, shows me the formID and it displays just fine. so i have no idea where i am going wrong.
<asp:GridView ID="gvHistory" runat="server" DataSourceID="ObjectDataSource"
AutoGenerateColumns="False" CellPadding="10" CellSpacing="5"
CssClass="userHistory" DataKeyNames="formID">
<Columns>
<asp:BoundField DataField="clientName" HeaderText="User" />
<asp:BoundField DataField="formName" HeaderText="Form" />
<asp:BoundField DataField="dateCreated" HeaderText="Date Created" />
<asp:BoundField DataField="dateRevised" HeaderText="Last Revision Date" />
<asp:BoundField DataField="dateSubmitted" HeaderText="Date Submitted" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="edit" runat="server" CausesValidation="false" CommandName="editForm"
Text="Edit" OnDataBinding="btnEdit_DataBinding" OnClick="btnEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="delete" runat="server" CausesValidation="false" CommandName=""
Text="Delete" OnDataBinding="btnDelete_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="formID" />
</Columns>
</asp:GridView>
protected void btnEdit_Click(object sender, System.EventArgs e)
{
Session["formID"] = gvHistory.SelectedDataKey.Value;
Label1.Text = Session["formID"].ToString();
}
If you are using CommandName with your item template then You can simply use Row_Command event, you don't need to create separate handler for button click.
protected void grdView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "editForm")
{
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
string value=grdView.DataKeys[row.RowIndex].Values["myDataKey"].ToString();
}
}
Button btn = (Button)sender;
GridViewRow gvrow = (GridViewRow)btn.NamingContainer;
if (gvrow != null)
{
//Get the Row Index
int rowIndex = gvrow.RowIndex;
//Get the DataKey value
Session["formID"] = gvHistory.DataKeys[rowIndex].Value.ToString();
Label1.Text = Session["formID"].ToString();
}

Categories