ASP GridView with Hover Menu, determining row that calls popup - c#

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

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

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

Doesnot firing OnSelectedIndexChanged event for Dropdownlist control existed in Child Gridview

I have parent gridview and child gridview, In child gridview I have one dropdown list, I need to fire the onselectedindexchanged event for that drop down but it is not firring because it is existed in the child gridview. If I place that dropdown in parent gridview then that selectedindexchanged is firing but I want to place that dropdown in child gridview and need to fire onselectedindexchanged event when user change the dropdown list value . In the below gridview image you can see the Status column in child gridview. It contains dropdown now I want to fire that dropdown seleted index changed event in code behind.
<asp:GridView ID="gvCountry" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" id="imgsymbol" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvBrokerdetails" runat="server" AutoGenerateColumns="false" CssClass="mGrid" OnRowCommand="gvBrokerdetails_RowCommand"
AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr" GridLines="None" AllowPaging="true">
<Columns>
<asp:BoundField DataField="BrokerName" HeaderText="Name" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="ddlStatus" runat="server" OnSelectedIndexChanged="ddlStatus_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="Include" Value="0"></asp:ListItem>
<asp:ListItem Text="Exclude" Value="1"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDeleteRow" runat="server" Width="25px" Height="25px" CommandName="CrossImageButton" CommandArgument='<%#Eval("BrokerId")%>' ImageUrl="~/images/cross-button.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CountryName" HeaderText="Country Name" />
</Columns>
</asp:GridView>
CodeBehind:
public void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
{
}
But the above is event is not calling. Is there any other process to achieve or I need to specify any new property in the code.
Find your gridview inside the RowDataBound Event of parent gridview
protected void gvCountry_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
GridView mygrid = e.Row.FindControl("gvBrokerdetails") as GridView;
}
}
than handle the event of mygrid it is your child grid you can handle any event you want or assign any property to it. an example of Selected_IndexChanged is below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView mygrid = e.Row.FindControl("gvBrokerdetails") as GridView;
mygrid.SelectedIndexChanged += new EventHandler(mygrid_SelectedIndexChanged);
}
}
void mygrid_SelectedIndexChanged(object sender, EventArgs e)
{
// Write your code here
}

Row Command Event of GridView is not working in ajax tab container

I want to download a file with link button of grid view. but the row command does not firing. the grid view is in Ajax tab container---Update panel.
Its working fine in Normal form without ajax tab container control.
Design Page:
<asp:TabPanel ID="TabPanel2" runat="server" HeaderText="Download" Height="150px" Width="500px">
<HeaderTemplate>
Download
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
Height="80%" Width="70%">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"/>
<asp:BoundField DataField="filename" HeaderText="filename" SortExpression="filename"/>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%#Eval("id")%>' ForeColor="White" CausesValidation="true" >DownLoad</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF6699" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
<br />
<br />
<br />
</ContentTemplate>
</asp:TabPanel>
Code Behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = ((GridViewRow)((LinkButton)e.CommandArgument).Parent.Parent).RowIndex;
if (e.CommandName=="Download")
{
Tabs.ActiveTabIndex = 1;
int Id = Convert.ToInt32((e.CommandArgument).ToString());
GridViewRow row = GridView1.Rows[Id];
string filename = row.Cells[1].Text;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
Response.TransmitFile(Server.MapPath("~/Docs/" +filename));
Response.End();
}
you need to set Download link as PostbackControl, try below code in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lb = e.Row.FindControl("LinkButton1") as LinkButton;
if(lb != null)
ScriptManager.RegisterPostbackControl(lb);
}

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