Call checkbox in C# backend - c#

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)
{
}
}
}
}

Related

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>

how to get control id from gridview in asp.net?

I need control id from grid view to use Trigger.
My code is here :
<asp:GridView ID="gvDetails" CssClass="table table-striped table-bordered datatables dataTable" DataKeyNames="folder_path" CellPadding="5" runat="server" AutoGenerateColumns="false" Width="100%">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="attachment_name" HeaderText="Attachment" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" runat="server" OnClick="DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="hideGridColumn" ItemStyle-CssClass="hideGridColumn">
<ItemTemplate>
<asp:HiddenField ID="hdnAttach_Id" Value='<%#(Eval("attachment_id").ToString())%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#2FBDF1" Font-Bold="true" />
</asp:GridView>
I need code like...
<Triggers>
<asp:PostBackTrigger ControlID="lnkDownload" />
</Triggers>
how to get "lnkDownload" id from gridview?
Exception :
You need to register each and every LinkButton as an PostBackTrigger. After each row is bound in your GridView, you'll need to search for the LinkButton and register it through code as follows:
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lb = e.Row.FindControl("lnkDownload") as LinkButton;
ScriptManager.GetCurrent(this).RegisterPostBackControl(lb);
}
And need to call this on RowDataBoundevent.
You can access the controls from the grid view using the findcontrol method
foreach(GridViewRow row in gvDetails.Rows)
{
if(row.RowType == DataControlRowType.DataRow)
{
LinkButton linkButton = (LinkButton )row.FindControl("lnkDownload");
//Your other code
}
}
I've recently encountered this problem as well.
You can find a control by doing e.row.findcontrol("NameOfControl").
Since I don't fully know what you intend to do, you can retrieve the ClientID by finding the control. Then you can specify the ID of the button by saying Button.ClientID. This will display the ContentHolder1_gridview_0_button_0.
To add attributes, you can do button.Attributes.Add("attribute", "#" + button.ClientID);
The following code is something I've fixed to have the following attribute added to the button. This is so that I can click a button and copy the textbox.
Example:
protected void gvListInventoryPassword_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HtmlButton buttonPass= (HtmlButton)e.Row.FindControl("buttonPass");
TextBox txtBox= (TextBox)e.Row.FindControl("txtBox");
buttonPass.Attributes.Add("data-clipboard-target", "#" + txtBox.ClientID);
}
}//End of gvListInventoryPassword_RowDataBound function

Reference specific checkbox in gridview

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
}
}

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();
}

ASP GridView with Hover Menu, determining row that calls popup

I have a GridView bound to an object datasource and a hover menu extender over that. On the panel that pops up I have two buttons - one for delete and one for edit. The problem I'm having is identifying which row triggered the hover menu so I know what to delete. I've searched all over the site and found similar issues but I wasn't able to apply them properly. I followed this video, and was able to get a hidden field to maintain the ID but only of the last row that was created, so my delete button always removed the last entry. I hope that was somewhat clear..
Here is my gridview code:
<asp:GridView runat="server" AutoGenerateColumns="False"
DataSourceID="source_Layout_view" ID="GridView1"
onrowdatabound="GridView1_RowDataBound"
onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="type" HeaderText="type" SortExpression="type" />
<asp:BoundField DataField="code" HeaderText="code" SortExpression="code" />
<asp:BoundField DataField="description" HeaderText="description"
SortExpression="description" />
<asp:BoundField DataField="position" HeaderText="position"
SortExpression="position" />
<asp:BoundField DataField="sequence" HeaderText="sequence"
SortExpression="sequence" />
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="img_edit" runat="server" ImageUrl='~/ui/images/wrench.png' Width="25px" Height="25px" />
<asp:HoverMenuExtender ID="gridview_options_extender" runat="server" PopupControlID="gridview_options_popup" TargetControlID="img_edit"
OffsetX="10" OffsetY="10" PopupPosition="Right" PopDelay="50" HoverDelay="50" >
</asp:HoverMenuExtender>
<asp:Panel ID="gridview_options_popup" runat="server">
<asp:Button ID="btn_popup_delete" runat="server" Text="Delete Unit" OnClick="deleteRow"/>
<br />
<asp:Button ID="btn_popup_edit" runat="server" Text="Edit Unit" />
<asp:HiddenField ID="tellmeRow" runat="server" Value='Eval("ID")'/>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is my code behind
protected void deleteRow(object sender, EventArgs e)
{
Button b = sender as Button;
Panel x = b.Parent as Panel;
HiddenField whatiwant = (HiddenField)x.FindControl("tellmeRow");
int idForDeletion = Int32.Parse(whatiwant.Value);
using (var context = new cocoEntities())
{
context.CoCo_Current.DeleteObject(context.CoCo_Current.Single(o => o.ID == idForDeletion));
context.SaveChanges();
}
Response.Redirect("default.aspx");
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HoverMenuExtender menu = (HoverMenuExtender)e.Row.FindControl("gridview_options_extender");
e.Row.ID = e.Row.RowIndex.ToString();
menu.TargetControlID = e.Row.ID;
}
}
}
Don't use button click handler to do some action on a GridView. Assign instead apropriate CommandName property value for button and handle GridView's RowCommand event. GridView.RowCommand Event

Categories