Asp GridView select a row then fire event - c#

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.

Related

Hyperlink in Gridview in c#?

I want to extract the article id from a gridview row when I click on the hyperlink. My goal is to be able to capture the article id field of a specific row when I click on the hyperlink in gridview.
This is what I tried so far but for some reason, it doesn't go to the codebehind when I click on the hyperlink.
<asp:GridView ID="Rssfeed" runat="server" AutoGenerateColumns="false" onrowcommand="grid_RowCommand" CssClass="Grid">
<Columns>
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
Articleid:
<asp:Label ID="Label1" Text='<%#Eval("articleid") %>' runat="server" />
<br />
Title :
<asp:Label ID="Label2" Text='<%#Eval("title") %>' runat="server" />
<br />
Link:
<asp:HyperLink ID="hlnkFile" runat="server" target="_blank" CommandName="Select" NavigateUrl='<%# Eval("link") %>' Text='<%# Eval("link") %>'></asp:HyperLink> <br />
Publicationdate:
<asp:Label ID="Label3" Text='<%#Eval("publicationdate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
public void grid_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = Rssfeed.Rows[index];
}
}
This example can help:
<ItemTemplate>
Link:
<asp:LinkButton ID="lbFile" CommandName="Select" runat="server"><%# Eval("link") %></asp:LinkButton>
</ItemTemplate>
code behind
public void Rssfeed_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
// get text from LinkButton e.g. URL as in question
string link = ((LinkButton)selectedRow.FindControl("lbFile")).Text;
// Redirect to the URL link
Response.Redirect(link);
}
}

How to know in which row a button is clicked in asp.net gridView

This is a simple gridView I m using in aspx web page
<asp:GridView ID="Order" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="none"
ItemType="MyProject.Models.TempList" SelectMethod="GetList" >
<Columns>
<asp:BoundField DataField="ItemID" HeaderText="ID" SortExpression="ItemID" />
<asp:TemplateField HeaderText="ItemName">
<ItemTemplate>
<asp:Label runat="server" ID="ItemName" Width="40" Visible="true" text="<%#: Item.Item.ItemName %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price(each)">
<ItemTemplate>
<%#: String.Format("{0:c}", Convert.ToDouble(Item.Item.UnitPrice))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<div style="float:left">
<asp:Button ID="DeleteBtn" runat="server" Text="Delete" OnClick="DeleteBtn_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have 2+ items in a list<> which is populating the gridView, how can I tell (in the codeBehind.cs) that which Row the "DeleteBtn" was clicked on?
I was using a for loop to iterate every item in gridView using Rows[i] and used a check box to know which item wants to be deleted using a Update button.
But I want to do it directly on a custom created deletebutton.
Thanks in advance, I know I'm missing something silly.
The best way to do that is using CommandName and CommandArgument in your button declaration like that
<asp:Button ID="AddButton" runat="server" CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Add to Cart" />
you can pass any value in the case we pass the rowIndex, you can get a propertie from your object like that CommandArgument="<%# Eval("id") %>" after that you will handle the onRowCommand method
protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
}
}
hope it helps :)
Use the button's CommandArgument property; assign Container.DataItemIndex to it. Then use the OnRowCommand event of the gridview and grab the index.
Sample aspx:
<asp:Label runat="server" ID="lblMsg" />
<asp:GridView runat="server" id="gvSample" AutoGenerateColumns="false" OnRowCommand="PerformOperation">
<Columns>
<asp:BoundField DataField="RowValue"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandName="MyCustomCommand" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGrid();
}
}
private void PopulateGrid()
{
gvSample.DataSource = Enumerable.Range(0, 10).Select(i => new { RowValue = i });
gvSample.DataBind();
}
protected void PerformOperation(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyCustomCommand")
{
var rowIndex = int.Parse(e.CommandArgument);
lblMsg.Text = string.Format("Button on row index: {0} was clicked!", rowIndex);
}
}
Let the button field be given a CommandName, say for example a unique string myCommandName in the Edit columns dialog box. Don't worry about the CommandArgument. Then, in the Grid view Row command event, you can check which button (i.e. column) is clicked by tracing the command name like if e.commandname = "mycommandname", at the same time the CommandArgument will also be available as String and all we have to do is to converttoint32, something like intSelectedRow = convert.ToInt32(e.CommandArgument) which will give us the selected row's index.

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

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

About ASP.NET Gridview

Hi I need help implementing a logic using Gridview control in c#.
I have a gridview and it has many rows. Each row has a Button to click for the user. On each button click i am updating the selected record in the database. Now once row is updated, I need to hide that button to prevent reaction just for that particular row.
1. If i use this
<asp:CommandField ShowEditButton="True" EditText="select" />
, I can't make this hide.
2. If I use this
<asp:TemplateField HeaderText="Your Action">
<ItemTemplate>
<asp:Button
ID="btnAccept"
runat="server"
Text="Accept"
OnClientClick="return confirm('Are you sure you want to Accept this offer?');"
onclick="btnAccept_Click" />
</ItemTemplate>
</asp:TemplateField>
, I can't get the selected row index.
I hope i have cleared what i wanna ask. Thanks in advance.
Use Button control's CommandArgument property specify the row user clicked :
<asp:TemplateField HeaderText="Your Action">
<ItemTemplate>
<asp:Button
ID="btnAccept"
runat="server"
Text="Accept"
OnClientClick="return confirm('Are you sure you want to Accept this offer?');"
CommandName="Accept"
CommandArgument='<%# Eval("RowId") %>'
onclick="btnAccept_Click" />
</ItemTemplate>
</asp:TemplateField>
At code behind :
void btnAccept_Click(Object sender, CommandEventArgs e)
{
if (e.CommandName == "Accept")
{
string rowId = e.CommandArgument;
}
}
Continuing on Canavars solution for 1):
void btnAccept_Click(Object sender, CommandEventArgs e)
{
if (e.CommandName == "Accept")
{
string rowId = e.CommandArgument;
((Button)sender).Visible = false;
}
}

Categories