Add image button to gridview databound dynamically - c#

I am displaying a gridview which should display a column containing image button.
How can I add image button to gridview row dynamically?
I don't want to enter by using template field from design field of the gridview. As this is image button I should be able to capture the event of the same.How to do the same?

i think you can add image to your edit and delete buttons from .aspx file also, i just tried and got it..
1.firstly make the gridview and then add activities like OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting"
i ma showing you jow to add images to edit and delete button for "update" and "cancel" you can proceed in the same way..
now go to source of gridview..
you will see code like this
<asp:CommandField ShowEditButton="True"/>
<asp:CommandField ShowDeleteButton="True"/>
after that change few things like add
<asp:CommandField ShowEditButton="True" ButtonType="Image" EditImageUrl="~/uploads/edit.png" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Image" DeleteImageUrl="~/uploads/delete.png" />
And after that make sure to save your images in 45 * 25 sizes only , and save it in any folder and remember to specify the path as i have done here , my folder is uploads.
Note: don't store images in App_data , it is for storing .mdf database files , any images will not work for you.. if the images is not showing in drop down list while adding imageurl try to add its path physically.

I think you can use template field for this. What you have to do is at the GridView RowDataBound event find the ImageButton you added in the template field and then give an ID or Row number or something which you can use to identify which row the ImageButton is in, as an Attribute of the ImageButton.
You can use this place to give the ImageUrl as well a sample would look like the below one.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imgbtn = (ImageButton)e.Row.FindControl("imgbtn1");
if (imgbtn != null)
{
imgbtn.Attributes["id"] = e.Row.RowIndex.ToString();
}
}
}
then you can create the click event for ImageButton. In that you can get the id/rowindex of the image button which was clicked and do what ever you want. Event may look like the below
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = (ImageButton)sender;
string rowindex = btn.Attributes["id"];
}
then in the GridView template field you can add the click event to ImageButtons onClick event. This may look like the below
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:ImageButton runat ="server" ID="imgbtn1" onclick="ImageButton1_Click"/>
</ItemTemplate>
</asp:TemplateField>

Related

How to set 'mouseover' event for per gridview row?

I'm using ASP.NET (C#). I have designed a gridview and loaded data from database (SQL Server). That's ok.
Here is advanced requirement:
-> The database contains a field that it cannot be showed while debugging. Because I had wrote:
<asp:BoundField DataField="course_group" HeaderText="Course group" SortExpression="course_group" HeaderStyle-CssClass="hidden" ItemStyle-CssClass="hidden" />
In css:
.hidden
{
display: none;
}
-> Now, I wanna get the value of course_group and set it into gridview row as a "Tooltip". Like this:
Visit W3Schools.com!
I know the way to write a link tooltip, but not for gridview row tooltip.
I think it's difficult, because you might want to many different tooltip text for all gridview rows
Is there anyway to do that?
Can you give me any C# code behind solution (mouseover event) or CSS/Javascript code solution (hover event)?
Thank you!
Try:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.ToolTip = (e.Row.DataItem as DataRowView)["Description"].ToString();
}
}
Reference Here

Passing data from gridview as session

I've a gridview with client ID, client name, client contact number and a hyperlink to client detail.
I would like to pass selected clint ID to another asp page (clientDetail.aspx & ClientContact.aspx).
I'm thinking of passing the clientID as session. But how do i go about doing this? Can someone guild me on this as im quite new to this.
& how do i use the passed data in clientDetail.aspx & ClientContact.aspx?
Thanks in advance for your help.
Add two new columns of type HyperLinkField to your gridView as follows. Now clientID is passed as QueryString. One link is here
<asp:HyperLinkField DataNavigateUrlFields="ClientID"
DataNavigateUrlFormatString="~/ClientDetails.aspx?id={0}"
Text="Client Details" />
Assuming that you are selected the grid row with a button or link button you could use the OnRowCommand event
When you wire into this event you can pick out the value you want from the selected item then save it into the Session which will then be available for subsequent pages. In the below exampel I've assumed the value is in a label field so you can pick it out of that control.
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblMyValue = (Label)e.Row.FindControl("lblMyValue");
Session["myValue"] = lblMyValue .Text;
}
}
There are other variants of this for instance you could store the value you are interested in in the CommandArgument property of the button that you use to select the row. The command argument will then be available in the RowCommand event
void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string arg = e.CommandArgument;
//.. put into session here
}
And there are alternatives using different events for instance you could use the DataKeys collection of the GridView to store the value you are interested in and pick out the value from there
Markup fragment
<asp:gridview id="CustomersGridView"
//.. more properties
datakeynames="myID"
onselectedindexchanged="MyGridView_SelectedIndexChanged"
runat="server">
Code behind
void MyGridView_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = MyGridView.SelectedIndex;
Session["myValue"] = CustomersGridView.DataKeys[index].Value.ToString();
}
There are a number of alternatives to get this working. I would use the first one detailed if it were me - I've always found it easiest to get to work. You can make the label hidden with Css if you want - if it isn't suitable for the UI. Or use a hidden field (with runat="server"). I'm going to stop - I'm risking confusuing by just typing on.
You should be able to evaluate the clientid field of the asp.net gridview in the navgiate url of the hyperlink and pass it as a query string like so:
<asp:gridview id="OrdersGridView"
datasourceid="OrdersSqlDataSource"
autogeneratecolumns="false"
runat="server">
<columns>
<asp:boundfield datafield="ClientID"
headertext="Client ID"/>
<asp:boundfield datafield="ClientName"
headertext="Client Name"/>
<asp:boundfield datafield="ClientContact"
headertext="Client Contact"/>
<asp:hyperlinkfield text="Details..."
navigateurl="~\details.aspx?clientid='<%# Eval("ClientID") %>'"
headertext="Order Details"
target="_blank" />
</columns>
</asp:gridview>

Dynamically adding a command button to a GridView

I'm having an issue with trying to add a button to my grid. My GridView is first loaded with data in the PageLoad event.
I'm then taking the data in the first cell of each row, and creating a button that will link to a URL. To get the URL, I have to run a query with the data in the first cell as a parameter. I was doing this in the RowDataBound event at first, but hitting that query for every row was making it really slow.
So I decided to add a button that would retrieve the URL only when you clicked the button.
Here's my GridView:
<asp:GridView ID="gvResults" runat="server"
OnRowDataBound="gvResults_RowDataBound"
OnRowCommand="gvResults_RowCommand">
</asp:GridView>
And my code:
protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
LinkButton lb = new LinkButton();
lb.CommandArgument = e.Row.Cells[0].Text;
lb.CommandName = "NumClick";
lb.Text = e.Row.Cells[0].Text;
e.Row.Cells[0].Controls.Add((Control)lb);
}
}
protected void gvResults_RowCommand(object sender, CommandEventArgs e)
{
switch (e.CommandName.ToLower())
{
case "numclick":
string url = GetUrl(e.CommandArgument.ToString());
Response.Redirect(url);
break;
default:
break;
}
}
The grid generates fine, the button gets added to the grid for each row. But when I click on it, the RowCommand event doesn't fire, and the page just refreshes.
Does anyone know what the issue is?
Why use a dynamic button at all? You can easily put the linkbutton directly into the markup of the gridview (as long as you don't mind using a template field) and there will be no need to mess around with the RowDataBound event.
Your markup would look something like the following:
<Columns>
<asp:TemplateField HeaderText="SomeHeaderText">
<ItemTemplate>
<asp:LinkButton ID="lnkBtn" runat="server" CommandName="NumClick" CommandArgument= '<%# (string)Eval("dbValue") %>' Text='<%# (string)Eval("dbValue") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
<asp:BoundField></asp:BoundField>
</Columns>
Add breakpoints to the RowCommand event and make sure that you can hit the breakpoints.
The problem may lie elsewhere.
Also, make sure that you're not databinding on postback.
You have a big trouble with your code. It's pretty hard for me to explain what's your big mistake, but I can easily tell you how to fix.
The problem is that you generate a new button inside the RowDataBound event, definitely the wrongest choice. The button gets rendered because it exists after that event when page renders, but doesn't exist before data binding. If you bind data everytime you load the page (even during postback) the button still gets rendered because you generate a new button.
But since the button doesn't exist before data binding, it cannot raise events. You must declare the button from markup into a template of GridView, then access it not by using new LinkButton() but by using e.Row.Cells[0].FindControl("buttonId") and set its text. Then, you have to set its markup in order to fire its own Command event (not RowCommand) and handle it as you used (don't forget to set CommandArgument during data binding)
[Edit] I also made a mistake: controls inside data bound controls also don't exist before data binding. But they are initialized not with new Control() (by the private methods of data bound control) but with Page.LoadControl(typeof(Control)). That's the first thing you must fix when you load controls dynamically!!
Because the control is added dynamically on databind and you have to databind the gridview for each postback, the control being "clicked" is different each time. The event doesn't fire because at the time it needs to fire it doesn't exist as it did in the last iteration of the page.
I notice you don't have any logic determine if the button should be there, and it always goes into cell[0].
You should place this button into a TemplateItem so that it exists properly. If you have a need to do it in code-behind, you are probably better served doing it in the RowCreated event.

Select from db, making icons from the items

What I'm trying to do is basicly what this photo shows.
When I select something from the treeview it passes a parameter to a linq command that selects some data from the database. For every item in the selection I want to make a Icon and a text that represents if the item is a folder or a file.
When I push the Icon or the Link i want it to do the same as i would push the treeview, pass a parameter to a linq command that selects again from the database and populates the placeholder.
The way I'm doing this now is to make at runtima a Panel that holds the ImageButton and LinkButton. Then i add the Panel to the ContentPlaceHolder.
The problem with this that it does it every time i select something new and also i cant get it to work if the push the icon or the linkbutton, only the from the treeview.
Could i use some controller and css to get this look for the Icons ?
Is there another better way ?
This is basicly the same system as the Explorer uses in Windows, Treeview shows only the folder but the window shows the folders and files. When i click a folder that folder opens up and the main window is populated with items that are inside that folder. If i click a file a editor opens up with the contents of the file.
Not sure I understand you question 100% but I think I got the gist.
I'm assuming that you want the folders first, then the files. I would create two repeaters in this area, one to hold the Folder Image and link buttons, and the other for the file image and link buttons.
Break your linq command into two queries, one to get the folders and one for files. Then just bind the repeaters to the corresponding repeaters.
Here's a bit of code to get you started:
<asp:Repeater ID="rptFolders" runat="server" OnItemCommand="rptFolders_ItemDataBound">
<ItemTemplate>
<div>
<asp:ImageButton ID="btnImage" runat="server" />
<asp:LinkButton ID="btnLink" runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
And the code behind after calling DataBind():
protected void rptFolders_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Book book = (Book)e.Item.DataItem; //Or whatever your passing
ImageButton btnImage = e.Item.FindControl("btnImage");
LinkButton btnLink = e.Item.FindControl("btnLink");
btnLink.Text = book.Name;
btnLink.Click += new EventHandler(FolderClicked);
btnImage.Click += new ImageClickEventHandler(FolderClicked);
}
}
You can obviously do whatever you want with Click Events, just added those in for good measure.
I would probably create a Folder and File Control and use those instead of the imagebutton / linkbutton combo, this way I could store more information about the Folder / File to access them later without having to do another query to get the ID or what not. But there are a million approaches to this, pick the one you think is best.
Let me know if you need more guidance w/ this solution, or if I didn't understand your question.
Happy Coding...
Sorry had to add as another Answer. Here's a quick sample of the folder user control.
Create your Control... Format however you want.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="FolderButton.ascx.cs" Inherits="FolderButton" %>
<div>
<asp:ImageButton ID="btnImage" runat="server" ImageUrl="yourfolder.jpg" />
<asp:LinkButton ID="btnTitle" runat="server" />
</div>
Add Properties and Click Event to the Code Behind (don't forget to fire the click event when your image and link buttons are clicked):
public partial class FolderButton : System.Web.UI.UserControl
{
public int DatabaseId { get; set; }
public string Name { get; set;} // you can even set your linkbutton text here.
public event EventHandler Click;
}
Create your Repeater of the FolderButton Controls:
<asp:Repeater ID="rptFolders" runat="server" OnItemDataBound="rptFolders_ItemDataBound">
<ItemTemplate>
<uc1:FolderButton ID="FolderButton1" runat="server" />
</ItemTemplate>
</asp:Repeater>
Set Folder Id on DataBinding:
protected void rptFolders_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Book book = (Book)e.Item.DataItem; //Or whatever your passing
FolderButton btnFolder = e.Item.FindControls("FolderButton1");
btnFolder.Name=book.Name;
btnFolder.DatabaseId=book.Id;
btnFolder.Click += new EventHandler(FolderClicked);
}
}
Lastly you can then do whever you want on the event Click:
void FolderClicked(object sender, EventArgs e)
{
int id = ((FolderButton)sender).DatabaseId;
/// Do something with your Id
}
Let me know if anything is unclear. This is just a quick freehand sample, so forgive any typos or bad practices... code is just for demostration purposes only.

GridView control with two asp:Command columns using the same command

I have an ASP.NET GridView control with two asp:CommandField columns that are both using the Select command to perform different tasks. How do I distinguish which column was selected in the OnRowCommand event when both return "Select" when I check the CommandName property of the GridViewCommandEventArgs object?
Here is my source code:
ASPX page:
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false" OnRowCommand="MyGridView_OnRowCommand">
<Columns>
<asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="Click Me!" />
<asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="No Click Me!" />
</Columns>
</asp:GridView>
Code behind:
protected void MyGridView_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
string x = e.CommandName //returns "Select" for both asp:CommandField columns
}
Use a button column instead that way you can specify the specific command names and work with it from there
<asp:ButtonField ButtonType="Link" Text="Click Me" CommandName="MyCommand1" />
<asp:ButtonField ButtonType="Link" Text="No Click Me" CommandName="MyCommand2" />
Then you can take action based on e.CommandName
Use the GridViewCommandEventArgs.CommandArgument property !
Well, first do you HAVE to use SELECt as the command? You could set that to something else that makes more sense.
Secondly, you could set the CommandArgument property to different values so you know which one is being clicked.
use the command argument property.
e.commandargument
Or you can dynamically create the button in the command field and set the commandName to anything you want.
in gridview_Load
for (int i = 0; i <= GridView1.Rows.Count - 1; i++) {
linkbutton btnedit = new linkbutton();
GridView1.Rows(i).Cells(3).Controls.Add(btnedit);
//the above is where you want the button to be on the grid
btndel.CommandName = "Select2";
btndel.CommandArgument = "whatever you want";
}
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "Select1" Then
//do stuff
End Sub
The answer you seek is simple and tricky. I had that problem too in my website project, so I surfed the internet for days and not found what I and you were needed.
One day I just thought about the problem alone and made experiments for hours and finally realized that the only easy way to know the column that the button was clicked is in the RowCommand event of the GridView in the CommandName property of the GridViewCommandEventArgs. More correctly probably and comfortable is to edit columns of GridView through the design mode and replace your Command fields to Button fields.
You can give any string/text you want to each button field in its CommandName, so in the RowCommand event you can know which was clicked. Button1 or Button2, but you don't want to give these strings, because you request something that the buttons should select and give to you, so the CommandName should be the word select, but it can be SELECT too and Select and selecT and etc.
The select command can be mention in the CommandName in many forms, and still the system will recognize it. So for example if you have two Button fields in the GridView, whose first CommandName is simply select and the other is SELECT, then when any of them is clicked the RowCommand event raises and
if (e.CommandName == "select")
{
Label1.Text = "You clicked first button";
}
else
{
Label1.Text = "You clicked second button";
}
and the SelectedDataKey of your GridView will contains the data you requested. What other people offered in their answer to differ in CommandName by setting button one to select_one and setting button two to select_two will help you to know if either select_one was clicked or other, but the SelectedDataKey of your GridView will remain null or DataKey instance that doesn't contain the information you need at all.
In other words, the buttons will not select any necessary information, so it is very important to follow my answer. It is the exact, perfect and great solution to your problem!

Categories

Resources