ListView Control With ImageButtons
While working on a new app I'm developing, I found the need for displaying a series of image buttons that repeated going left to right, not the traditional up and down of gridview/datagrid fame. Thankfully the new .Net 3.5 framework has a control that can do such a thing, the ListView. Below I will demonstrate how to create a ListView control, populate it with image buttons, and then capture when each button is clicked on in the code behind. This is also my first foray into using the ListView, so if you have comments or suggestions how to improve my example, please leave them in the comments for this post.
Seeing that this post is about creating a ListView, we’ll get right into that first.
<asp:ListView ID="productsList" runat="server"
<b>Image Buttons:</b><br />
<asp:PlaceHolder ID="itemContainer" runat="server" />
<asp:ImageButton ID="btnImage" runat="server"
ImageUrl='<%# DisplayImage(Eval("imageURL").ToString()) %>'
ToolTip='<%# Eval("imageDescription").ToString() %>'
CommandArgument='<%# Eval("imageID").ToString() %>'
Notice the section, which is something new with ListViews. Inside this section, you must include a PlaceHolder control, which is where the repeating section of your ListView will appear. The rest of what is included will appear before and after your repeated content. It’s a lot like how a MasterPage works.
The section represents the repeated section in your ListView. In my example, I am doing an ImageButton and also including a ToolTip description. The DisplayImage function used for the ImageURL is simply in order to set the directory of the image, as I like to institute a little order in my apps by keep images in separate folders from code. It’s a noble duty and I suggest you always do the same as well.
The includes text to be displayed if your DataSource doesn’t have any records. That should be pretty self explanatory.
To connect to a datasource, you can use any of the common methods used for DataGrids, Gridviews, etc. For this example, I put together a simple SQLDataSource. I’ll show the code, but give that this isn’t a new control, I’m not going to take the time to go through how it works. I’m sure you can Google and find that info if you really need it.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Webhost4Life %>"
SelectCommand="SELECT * FROM Demo_Images">
This article has been view 4473 times.