Add a clickable image to a GridView in ASP.Net - asp.net

I'm trying to add an delete image at the end of each row in a GridView. I want the user to be able to click the image to delete the row.
So I've used a HyperLinkField to create a link to another page which will delete the record:
<asp:HyperLinkField DataNavigateUrlFields="ID"
DataNavigateUrlFormatString="RemoveLine.aspx?ID={0}"
Target="_blank" />
The HyperLinkField doesn't contain an Image tag so I created a TemplateField with an Image inside.
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imageRemove" runat="server" ImageUrl="~/Images/smallcross.gif" />
</ItemTemplate>
</asp:TemplateField>
However the HyperLinkField and Image appear in different columns and the image has no click event.
Any way of combining the two?
I'm using ASP.Net 4.0.
Thanks in advance

Normally you need to identify which record you want to delete, you can use the CommadArgument property to identify the record's Id:
<asp:TemplateField HeaderStyle-Width="40">
<ItemTemplate>
<asp:ImageButton ID="ButtonDelete" runat="server"
ImageUrl="~/Imags/delete.png" OnClick="ButtonDelete_Click" ToolTip="Delete"
CommandArgument='<%#Bind("UserId")%>'/>
</ItemTemplate>
</asp:TemplateField>
protected void ButtonDelete_Click(object sender, EventArgs e)
{
ImageButton button = sender as ImageButton;
DeleteUserById(Convert.ToInt32(button.CommandArgument));
}

<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server"
ImageUrl="~/Imags/delete.png" OnClick="btnDelete_Click"
ToolTip="Delete row" CommandName="Eliminar" CommandArgument='<%#Eval("UserId")%>'/>
</ItemTemplate>
You can use the CommandArgument to pass the ID value of the selected row and perform
the desires results
// fires when the ImageButton gets clicked
protected void GridView1_ItemCommand(object sender, DataGridCommandEventArgs e)
{
if(e.Commandname ="Eliminar"){
this.Eliminar(Convert.ToInt32(e.CommandArgument));
}
}
// function to delete the record
private void Eliminar(int code)
{
//custom code to delete the records
}

How about an image button?
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="~/Images/smallcross.gif" onclick="ImageButton1_Click" />
</ItemTemplate>

you can wrap your image with a raw anchor tag , you get the same result.
<asp:TemplateField>
<ItemTemplate>
<a href="RemoveLine.aspx?ID={0}">
<asp:Image ID="imageRemove" runat="server" ImageUrl="~/Images/smallcross.gif" />
</a>
</ItemTemplate>
</asp:TemplateField>

Related

How to fetch the Value of a LinkButton in a GridView Template Field

I Have a LinkButton In a TemplateField In a GridView. The LinkButton is bound to database which shows the time save in database.All I want is to fetch each linkbutton time value and compare it to current time and if linkbutton time is less than current time ,make it disable.
Any pointers will be helpful.
Thanks in advance.
<asp:GridView ID="grdview" AutoGenerateColumns="false" runat="server" OnRowCommand="grdview_RowCommand">
<Columns>
<asp:BoundField DataField="AudiName" DataFormatString="Audi {0}" HeaderText="Audi Name" />
<asp:TemplateField HeaderText="StartTime">
<ItemTemplate>
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
CommandName="time"
CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>
<asp:HiddenField runat="server" ID="hf1" Value='<%#Eval("StartTime")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can use the OnRowDataBound event to hook into the data binding and disable the button.
Form
<asp:GridView ID="MyGridView"
OnRowDataBound="MyGridView_RowDataBound"
runat="server">
....
</asp:GridView>
CodeBehind
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the button
var linkButton = (LinkButton) e.Row.FindControl("MyLinkButton");
// Toggle enabled/disabled based on time
// Using the button text is probably a bad idea, but is used here for demonstration purposes
linkButton.Enabled = (Convert.ToDateTime(linkButton.Text) > DateTime.Now);
}
}
The code above has not been tested, but should give you an idea of how you can approach this.
You can set the Enabled property of LinkButton comparing with the current time:
<asp:LinkButton ID="lnkmovietime" runat="server"
Text='<%# Eval("StartTime") %>'
Enabled = '<%# ((DateTime)Eval("StartTime")< DateTime.Now )? false : true %>'
CommandName="time" CommandArgument='<%#Eval("AudiID") %>'>
</asp:LinkButton>

ASP- Get a GridRow value / OnClick method

I'm working on a C#/ASP 4.0 project where I'm trying to make a shopping cart application.
There is a GridView on my Products page that shows all of the items, and I want the user to be able to click an "Add to Cart" button field in this GridView which will, obviously, add an item to their cart.
I'm having issues actually setting an OnClick event for the gridview, though? That doesn't seem to be available in the Event menu in the Properties. Additionally, I can't seem to figure out how to get the specific row, either. I have method that does this...
int productID = Convert.ToInt32(GridView1.Rows[n].Cells[0].Text);
AddToCart(productID);
But I have no idea how to figure out n, or how to have this method get called when they click that ButtonField in the gridview.
You could do this:
First, add a template field to the gridview:
<asp:TemplateField HeaderText="Add to Cart">
<ItemTemplate>
<asp:Button id="bthAddToCart"
CommandArgument'<%#Eval("ProductID")%>'
OnClick="bthAddToCart_Click"
Text="Add to Cart"
runat="server"/>
</ItemTemplate>
</asp:TemplateField>
Now, add the handler for the Click event of the button:
protected void bthAddToCart_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
int productID = Convert.ToInt32(button.CommandArgument);
AddToCart(productID);
}
You can use the template fields like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="30px">
<ItemTemplate>
<asp:Button ID="btnAddToCart" runat="server" Text="Add To Cart" CommandName="AddToCart"
CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Data Found.
</EmptyDataTemplate>
</asp:GridView>
Then on your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int ProductID = Convert.ToInt32(e.CommandArgument);
AddToCart(ProductID);
}
}
Hope this helps! Good Luck!
Use the OnRowCommand event of the grid view. More details: here
You have to use OnRowCommand Event for Gridview. Use Following Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Header Text Here">
<ItemTemplate>
CONTROL TO SHOW COLUMN DATA
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="30px">
<ItemTemplate>
<asp:Button ID="btnAddToCart" runat="server" Text="Add To Cart" CommandName="AddToCart"
CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
In C# Code use following code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Add To Cart")
{
int ProductID = Convert.ToInt32(e.CommandArgument);
AddToCart(ProductID);
}
}

ASP.NET Grid View Problem

I have one gridview where I am passing the command argument as gridview row id for the Button I created for every row.
I want to display all the details of that row in the textbox according to the Row clicked.
<asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
onrowcommand="gvCategory_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#Eval("categoryId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatName" runat="server" Text='<%#Eval("categoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnModify" runat="server" Text="Modify" CommandName="Modify" CommandArgument='<%#Eval("categoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code.....
if (e.CommandName == "Modify")
{
int id = Convert.ToInt32(e.CommandArgument);
// I want the value to assgin for the selected row here
// I was previously fetching the data from database according id,but i want this frim the gridview of selected row.
}
I wrote a quick example of how to do what you're trying to do. It works for me.
The Example Solution
Default.aspx
<asp:GridView ID="myGridView" runat="server"
AutoGenerateColumns="False"
DataSourceID="StudentsDS"
DataKeyNames="ID"
OnRowCommand="myGridView_RowCommand"
OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="FullName" HeaderText="FullName"
SortExpression="FullName" />
<asp:BoundField DataField="ClassID" HeaderText="ClassID"
SortExpression="ClassID" />
<asp:CommandField ShowSelectButton="True" SelectText="Modify" />
</Columns>
</asp:GridView>
<asp:TextBox ID="txtStudent" runat="server" />
<asp:SqlDataSource ID="StudentsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Sandbox %>"
SelectCommand="SELECT * FROM Student"
/>
Default.aspx.cs
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
// do something here if you want, although not necessary
}
}
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
// show "FullName" field of selected row in textbox
txtStudent.Text = myGridView.SelectedRow.Cells[1].Text;
}
How It Works
Upon clicking "Modify" in a row, the textbox updates to show the FullName field of the selected row.
The important part is that instead of a TemplateField, use a CommandField with ShowSelectButton="True". Then do what you need to do in the SelectedIndexChanged event handler. Note that the SelectText of the CommandField is set to "Modify" as you desired. You can also set the ButtonType property of the CommandField to be button, image, or link.
Making It Better
I would also advise that instead of using a SqlDataSource as I have, you use an ObjectDataSource so that you can do something like
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
MyModelObject o = myGridView.SelectedRow.DataItem as MyModelObject;
txtStudent.Text = o.MyProperty;
}
You may also consider wrapping your GridView in an UpdatePanel to prevent full postbacks / page refreshes.
After you have the lineID, you select that line, and then you have the CategoryID on selected value
int iTheIndexNow = Convert.ToInt32(e.CommandArgument);
// select that line to see it visual as selected, and get the value on next line
gvCategory.SelectedIndex = iTheIndexNow;
// here is your categoryID that
//you can use to open your database with and get the text
gvCategory.SelectedValue // == categoryID
On GridView you must have set your KeyID
<asp:GridView DataKeyNames="categoryId" .... >

GridView: Get datakey of the row on button click

How can I get a value of the DataKeyName of a GridView Row when I have a button inside a row that have an OnClick event. In my OnClick event of my button I want to get a the DataKeyName of the row where the button resides.
Is this possible?
<asp:GridView ID="myGridView" run="server">
<Columns>
<asp:TemplateField HeaderText="Column 1">
<ItemTemplate>
... bunch of html codes
<asp:Button ID="myButton" UseSubmitBehavior="false" runat="server" Text="Click Me" onclick="btnClick_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In my codebehind
protected void btnClick_Click(object sender, EventArgs e)
{
// How can I get the DataKeyName value of the Row that the Button was clicked?
}
When I'm working with a GridView, I usually do not use the OnClick event for buttons. Instead, I use the OnRowCommand event on the GridView, and bind data to the CommandArgument property of the button. You can retrieve the command argument from the GridViewCommandEventArgs parameter of the event handler.
You can use the CommandName parameter to bind an arbitrary string to distinguish between any different kinds of buttons you have. Note that some command names are already used for other events, such as "Edit", "Update", "Cancel", "Select" and "Delete".
Update:
Here is an example, assuming the data key is called "ID":
<asp:GridView ID="myGridView" runat="server" OnRowCommand="myGridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Column 1">
<ItemTemplate>
... bunch of html codes
<asp:Button ID="myButton" runat="server" Text="Click Me" CommandName="ClickMe" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the code-behind:
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var datakey = e.CommandArgument;
// ...
}
You can bind the key to the CommandArgument property of the Button, and consume (sender as Button).CommandArgument property in the code

How do you bind a DropDownList in a GridView in the EditItemTemplate Field?

Here's my code in a gridview that is bound at runtime:
...
<asp:templatefield>
<edititemtemplate>
<asp:dropdownlist runat="server" id="ddgvOpp" />
</edititemtemplate>
<itemtemplate>
<%# Eval("opponent.name") %>
</itemtemplate>
</asp:templatefield>
...
I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //skip header row
{
DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp");
BindOpponentDD(ddOpp);
}
}
Where BindOpponentDD() is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in?
Thanks so much in advance...
Ok, I guess I'm just dumb. I figured it out.
In the RowDataBound event, simply add the following conditional:
if (myGridView.EditIndex == e.Row.RowIndex)
{
//do work
}
Thanks to Saurabh Tripathi,
The solution you provided worked for me.
In gridView_RowDataBound() event use.
if(gridView.EditIndex == e.Row.RowIndex && e.Row.RowType == DataControlRowType.DataRow)
{
// FindControl
// And populate it
}
If anyone is stuck with the same issue, then try this out.
Cheers.
I had the same issue, but this fix (Jason's, which is adding the conditional to the handler) didn't work for me; the Edit row never was databound, so that condition never evaluated to true. RowDataBound was simply never called with the same RowIndex as the GridView.EditIndex. My setup is a little different, though, in that instead of binding the dropdown programmatically I have it bound to an ObjectDataSource on the page. The dropdown still has to be bound separately per row, though, because its possible values depend on other information in the row. So the ObjectDataSource has a SessionParameter, and I make sure to set the appropriate session variable when needed for binding.
<asp:ObjectDataSource ID="objInfo" runat="server" SelectMethod="GetData" TypeName="MyTypeName">
<SelectParameters>
<asp:SessionParameter Name="MyID" SessionField="MID" Type="Int32" />
</SelectParameters>
And the dropdown in the relevant row:
<asp:TemplateField HeaderText="My Info" SortExpression="MyInfo">
<EditItemTemplate>
<asp:DropDownList ID="ddlEditMyInfo" runat="server" DataSourceID="objInfo" DataTextField="MyInfo" DataValueField="MyInfoID" SelectedValue='<%#Bind("ID") %>' />
</EditItemTemplate>
<ItemTemplate>
<span><%#Eval("MyInfo") %></span>
</ItemTemplate>
</asp:TemplateField>
What I ended up doing was not using a CommandField in the GridView to generate my edit, delete, update and cancel buttons; I did it on my own with a TemplateField, and by setting the CommandNames appropriately, I was able to trigger the built-in edit/delete/update/cancel actions on the GridView. For the Edit button, I made the CommandArgument the information I needed to bind the dropdown, instead of the row's PK like it would usually be. This luckily did not prevent the GridView from editing the appropriate row.
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" runat="server" ImageUrl="~/images/delete.gif" AlternateText="Delete" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Delete" />
<asp:ImageButton ID="ibtnEdit" runat="server" ImageUrl="~/images/edit.gif" AlternateText="Edit" CommandArgument='<%#Eval("MyID") %>' CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibtnUpdate" runat="server" ImageUrl="~/images/update.gif" AlternateText="Update" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Update" />
<asp:ImageButton ID="ibtnCancel" runat="server" ImageUrl="~/images/cancel.gif" AlternateText="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
And in the RowCommand handler:
void grdOverrides_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
Session["MID"] = Int32.Parse(e.CommandArgument.ToString());
}
The RowCommand, of course, happens before the row goes into edit mode and thus before the dropdown databinds. So everything works. It's a little bit of a hack, but I'd spent enough time trying to figure out why the edit row wasn't being databound already.
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (grdDevelopment.EditIndex == e.Row.RowIndex && e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
}
}
Try this one
This will help u
This code will be do what you want:
<asp:TemplateField HeaderText="garantia" SortExpression="garantia">
<EditItemTemplate>
<asp:DropDownList ID="ddgvOpp" runat="server" SelectedValue='<%# Bind("opponent.name") %>'>
<asp:ListItem Text="Si" Value="True"></asp:ListItem>
<asp:ListItem Text="No" Value="False"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("opponent.name") %>'></asp:Label>
</ItemTemplate>

Resources