Tag Archives: ListView

[RESOLVED]Problem in understanding an example on the pro Asp.net MVC 5 book

I am reading a book named Pro Asp.net MVC 5 , which is great , but I found the following code, which will show a lsit of products based on the selected category, and calculate the total number of items, as follow:-

public ViewResult List(string category, int page = 1) {
ProductsListViewModel viewModel = new ProductsListViewModel {
Products = repository.Products
.Where(p => category == null || p.Category == category)
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
PagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = category == null ?
repository.Products.Count() :
repository.Products.Where(e => e.Category ==

But I got confused on why we need to do the following:-

TotalItems = category == null ? repository.Products.Count() : repository.Products.Where(e => e.Category == category).Count()

 and not just saying 

TotalItems = Products.count();

Because we already retrieve the Products based on the category, and there is no need to re-retrivng them to calculate their total !! Can anyone advice

The "Products" property of the ProductsListViewModel has all products where the category matches the category passed into the action if one is, but all products if it isn’t.  The line in question does the same thing.

x = a ? b : c

this means that if "a" is true then x will be "b" otherwise it will be "c".

So TotalItems will be just the number of products in the repository if no category has been passed in, but the number of products where the product has that category if a category has been passed in.

[RESOLVED]Eager Load – Determine if ICollection Empty

I have a Person table and each person can have many or no Papers.

So there is a one to zero or many relationship between Person and Papers

How can I determine if a person has at least one paper in the where clause below of my controller?

public ActionResult PaperImages(string searchTerm = null, int page = 1)
            if (page < 1)
                return HttpNotFound();

            var people= db.Person
                .Include(p => p.Papers)
                .Where(p => p.Department_id == 496

                    && p.Papers.Select(p => p.File_Name.Contains("."))

                    && (searchTerm == null || p.Last_Name.Contains(searchTerm)))
                .Select(a => new PersonListViewModel
                    Person_ID = p.Person_ID,
                    Last_Name= p.Last_Name,
                    Papers= p.Papers
                .ToPagedList(page, 10);

            return View(people);


I am having difficulty with the following line of code:

                    && p.Papers.Select(p => p.File_Name.Contains("."))

I want to determine if the Person has any Papers in the where clause – if not then do not show that person on this list.

I just ended up using

&& p.Papers.Count >= 1

List view alignment

I have a list view inside of 2 divs .They are the same width, and the second div lines up to the center of the first, but the list view is ou

 <div style="margin-left:10px; margin-top:10px;  width:220px; background-color:lightseagreen; height:auto;">
               <div style="margin:auto; margin-top:10px; width:190px;  height:auto;">
            <asp:ListView ID="lvdogglogs" runat="server" OnItemDataBound="lvdogglogs_ItemDataBound" style="width:190px; " GroupItemCount="4" GroupPlaceholderID="gpid">
[the grid description]</div></div>

of bounds I lines up 50px to the right of the divs? What am I doing wrong?

Hi DieseIDave,

Thanks for your post.

Firstly, I recommend to check the structure of the elements in your webpage via
Developer Tools.

Secondly, you could also show us your complete code, then we will reproduce your problem and try our best to resolve it.

Best Regards,

Fei Han

[RESOLVED]Table inside Table


 I want to design a concept similar like nested gridview.But i dont want table inside a table. Is there any way to do it.pls help.

You can use a listview which allow you to control the rendered html. You might use divs instead. 

You can show/hide div also insted of table.

dear komaldparekh,

                                can you give me a example for this.

Hi vignesh,

Thanks for your post.


You can show/hide div also insted of table.

The <div> element and <table> element are often used as a layout tool, If I don’t misunderstand, komaldparekh recommend to use <div> element instead of <table> element. Besides, here is a good article which describes why do developers move form table-based
website structures to div-based structures, you could refer to it.

If you have any question about this issue, please post back freely.

Best Regards,

Fei Han

What sort of data are you displaying in your grid/nested data?

If it’s tabular data, use a table – that’s what tables are for. A gridview is typically used for displaying tabular data so it makes sense to render it as a table. If you have nested data that is also tabular, that should also be rendered as a table. 

[RESOLVED]How do I remove an item from a listview with Jquery?

I want to remove an item from a ListView with Jquery.  How do I do that?

Could you provide an example of what your ListView might look like? Or an example of what your rendered markup (within your page) might look like?

Once you get a feel for how to use jQuery selectors to target specific elements, it can make their removal quite easy. It would be much easier to have some existing data to work with, but if you don’t, I could throw together a quick example.

Actually, I’ll just throw together one real quick.

Let’s say you have a ListView that looks like the following :

<form id="form1" runat="server">
        <!-- Your List View -->
        <asp:ListView ID="YourListView" runat="server">
                <div id="element-<%# Eval("Value") %>">
                    <%# Eval("Value") %>

This is fairly simple as you can tell. It simply generate a <div> element for each value in your collection and gives an id to that element of "element-x", where x is the value. You could use the following code to handle this mapping (for example purposes)

public partial class Example : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            // Bind 25 integers to the List
            YourListView.DataSource = Enumerable.Range(1, 25).Select(w => new Widget(w));

// An example class to demonstrate data binding
public class Widget
        public int Value { get; set; }

        public Widget(int value)
            Value = value;

This will generate something that looks like this :

Each of these elements will have markup that looks like this :

<div id="element-1">

Using this, you can easily use jQuery to select a particular element based on it’s name by just prefacing the item with ‘element-’. So if you wanted to remove the 5th element, you would use :

<!-- Example jQuery Reference -->
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
        $(function() {
            // When the page loads, remove the fifth element

This is a very basic example, however you could easily alter it to target elements by other properties or their actual indices themselves. It ultimately just depends on how your ListView is structured at present.

I always appreciate your help Rion!

Here is an example. I didn’t provide all of the html, but here is where the delete control is.

                    <tr class="even">
                        <td style="width: 50px; white-space: nowrap">
                            <asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~//images/icons/Delete.png" CssClass="lvBtnDelete"  CommandName="Delete" ToolTip="Click to Delete this Item" OnClientClick="listViewDelete('ListViewContacts');"/>
                            <asp:ImageButton ID="btnSelect" runat="server" ImageUrl="~//images/icons/Select.png" CssClass="lvBtnSelect" CommandName="Select" ToolTip="Click to Make this choice a Contact for this Loan"/>

when I click on btnDelete, I want to delete the item in the displayed listview. The way it works now, I have to do a postback and run c# codebehind to do it.  I would like to avoid that.

Do you actually want to delete the item from the datasource that is populating your ListView or just remove it from the actual page (without having a postback)?

I was going to let the codebehind delete it as it does when a PostBack is done. But just have it out of the ListView Immediately when it is deleted.

List page template column generator problem


I use column generator in List page template to generate command column, hide some columns, set column alignment and size, etc(with some attribute I defined). There is a problem about ViewState and some entities sort and paging functionality causes the error
that contains:

Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back
must match the type and position of the controls added during the initial request.

Based on the following threads I think the problem is the timing of setting column generator:



I set column generator in Load event of List page template because in Init event of Page and GridView It has no effect. The solution provided in the first thread does not work becuase I do more than hiding columns and the second solution is for prior 4.0
.Net framework. Any solution to resolve the issue.


Hi ali, I use column generators all the time and have no issues could you post your code please?


The code follows. There are some extension methods that hopefully are clear to understand:

    public class CustomizedAutoFieldGenerator : IAutoFieldGenerator
        private MetaTable table;
        public IEnumerable<MetaColumn> SkipList { get; set; }
        public CustomizedAutoFieldGenerator(MetaTable metaTable)
            table = metaTable;
            SkipList = table.Columns.GetSkipList(PageActionType.List);
        public ICollection GenerateFields(Control control)

            var filteredSortedColumns = table.Columns.Where(c => c.IncludeField(SkipList))
                                                     .OrderBy(c => c.ColumnOrdering())
                                                     .ThenBy(c => c.Name);
            List<DynamicField> fields = new List<DynamicField>();

            foreach (MetaColumn column in filteredSortedColumns)
                Unit unit = column.GetWidth();
                if (unit == Unit.Empty)
                    object columns = column.GetUIHintParameter("Columns");
                    if (columns != null)
                        unit = new Unit((int)columns, UnitType.Em);
                        unit = new Unit(Math.Max(1, column.ColumnType.GetColumnCount() / 2), UnitType.Em);

                DynamicField field = new DynamicField()
                    DataField = column.Name,
                    HeaderText = column.ShortDisplayName,
                    SortExpression = getSortExpresion(column)
                field.ItemStyle.Width = unit;

                if (column.ColumnType.IsBoolean())
                    field.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                field = applyUIHintParameters(column, field);

            if (table.PrimaryKeyColumns.Count > 0)
                DynamicField commandField = getCommandField();
                commandField.ItemStyle.Width = new Unit(11, UnitType.Em);
            return fields;
        private string getSortExpresion(MetaColumn column)
            if (column.UIHint == "Image")
                return string.Empty;
            return column.Name;

        private DynamicField applyUIHintParameters(MetaColumn column, DynamicField control)
            object[] parameters = column.GetUIHintParameters(new string[] { "HorizontalAlign", "VerticalAlign" });
            if (parameters[0] != null)
                control.ItemStyle.HorizontalAlign = (HorizontalAlign)parameters[0];
            if (parameters[1] != null)
                control.ItemStyle.VerticalAlign = (VerticalAlign)parameters[1];

            return control;
        private DynamicField getCommandField()
            // get the first primary key field                
            DynamicField ctrl = new DynamicField();
            ctrl.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            ctrl.HeaderText = Resources.General.Commands;
            ctrl.DataField = table.PrimaryKeyColumns[0].Name;
            ctrl.SortExpression = string.Empty;
            ctrl.UIHint = "GridCommand";
            return ctrl;


Hi Ali, I suspect it’s the command field that is causing the issue I suggest commenting that out an testing.

Hi Stephen, It still does not work.

I’ll have to try running here in a sample project, as I don’t use field generators for my project any more I only use them to set the item style wrap on columns I do all my field filtering in custom meta models. An I see you are doing some clever stuff in
there I’ll look late next week.


Sadly, I’m going to be away next week now so it will have to wait until I get back if I can’t look by Thursday


Hi Steve

I think there is no way except reimplementing List Page template with ListView. What’s your opinion?

Sorry Ali, I must be being a little Dumb I think the issue is the Command Column try removing that from the Field Generator and see what happens. I remember I have tried moving the Command column this way and had issues in the end I gave up and I only use
the IAutoFieldGenerator to handle Column Wrap and other formatting. I use a custom Metamodel to do field and Filter ordering etc.

The problem was that I need command field and it didn’t work until I transferred field generator from Init event to Load event and then there was the problem of ViewState. Provided this situation I think there is no way except using ListView in list templte.
I saw your MetaModel approach but it does not work with my other requirements.

Thanks anyway

OK I got you and see what you need, there may be a way around this but at the moment I’m not sure but will get back to you if I find a solution.


[RESOLVED]Populate the Comma-seperated Ids to gridview using JQUERY

i am having a gridView. i need to throw a popup when User clicks a link button inside the gridview in the 2nd column. The 6th column of a gridview is having comma – seperated Ids. All i need to do is genrate a popup when user clicks the link button having
a listview or gridview. and then show these comma seperated Ids over it …. HELP!

 i have managed to get the Ids(comma seperated)..from the 6th column. but my problem starts when i need to populate these values (split by ,) to a gridview.. i want to do and my need is to do all this work through Jquery….

i would like to add the further thing is the 6th column i mentioned is set to visible = "FALSE"

First of all, putting CSVs in a seperate column and hiding this column will not work. Instead of this, place a HiddenField control in any column wich is going to be visible and put these CSVs in this HiddenField control.

Now, on clicking a button, call a JavaScript fnuction to populate these CSVs in the popup.

To split the CSVs, use: var array
= myString.split(‘,’); 

To populate these CSVs in the popup, you have to do a work arround of creating a HTML Table dynamically and showing it in popup.

Refer this link for creating and populating the HTML table dynamically using jQuery:


Thank u show much.. :)

now i have one more Problem.

my Gridview is inside a Web user Control. In the User control , i am having a gridview.
The control is Placed inside an aspx page. How to write the JQUery to exactly refer the gridview inside the Web user control….

if the gridview Would not inside the Web User Control I could Easliy write..

$(document).ready(function () {

        $("#<%=gdvwJobForMergeAndPalletize.ClientID%> tr").not(‘:first’).hover(function () {
            $(this).css("background-color", "#cccccc");
        }, function () {
            $(this).css("background-color", "#ffffff");

But How to Refer the Grid view in side the Web Control using the Jquery in ASPX parent Page.

Look into the ViewSource of the webpage and find the rendered client id of the GridView in the User Control.

Use this rendered client id of the GridView in your jQuery function.


$("#<%=gdvwJobForMergeAndPalletize.ClientID%> tr").not(‘:first’).hover(function () {

Here, instead of <%=gdvwJobForMergeAndPalletize.ClientID%> use the static rendered client id.

i am not getting this done.. i dont knw why.. may be i am putting a wrong syntax


$("ctl00_masterContentPlaceHolder_MergeJobPanel_gdvwJobForMergeAndPalletize tr").not(‘:first’).hover(function () {
                        $(this).css("background-color", "#cccccc");
                    }, function () {
                        $(this).css("background-color", "#ffffff");
but nothing is happening on row hover ..:(

this is the html rendered Control Id = "ctl00_masterContentPlaceHolder_MergeJobPanel_gdvwJobForMergeAndPalletize"


$("ctl00_masterContentPlaceHolder_MergeJobPanel_gdvwJobForMergeAndPalletize tr").not(‘:first’).hover(function () {

Replace it with

$(‘#ctl00_masterContentPlaceHolder_MergeJobPanel_gdvwJobForMergeAndPalletize tr’).not(‘:first’).hover(function () {


UpdateProgress and the combination of a ListView with Modalpopupextender and Confirmbuttonextender

The UpdateProgress does not show when I’m using the combination of a ListView with Modalpopupextender and Confirmbuttonextender.

I want the UpdateProgress to show when I’m clicking the OKcontrolid button. And this is working fine:

<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:modalpopupextender id="Modalpopupextender1" runat="server" cancelcontrolid="ButtonDeleteCancel" okcontrolid="ButtonDeleleOkay" targetcontrolid="Button1" popupcontrolid="DivDeleteConfirmation" backgroundcssclass="ModalPopupBG" />
<asp:confirmbuttonextender id="Confirmbuttonextender1" runat="server" targetcontrolid="Button1" enabled="True" displaymodalpopupid="Modalpopupextender1" />

The page does it’s ClientSide magic with showing the PopUp, and when I click the OK button, the UpdateProgress starts fine.

As soon as I put it in a ListView ItemTemplate it does not work. The PopUp shows, but when I click on the OK button, the UpdateProgress does not show.

<asp:ListView runat="server" id="gwUnitInfo" GroupItemCount="1" DataSourceID="sqlUserRoles">
          <table class="gridview_TemplateComputer">
          <tr ID="groupPlaceholder" runat="server"></tr>
         <tr id="productRow">
         <td ID="itemPlaceholder" runat="server"></td>
    <td class="cssItemLabel">
       <asp:Button ID="Button1" runat="server" Text="Button" />
       <asp:modalpopupextender id="Modalpopupextender1" runat="server" cancelcontrolid="ButtonDeleteCancel" okcontrolid="ButtonDeleleOkay" targetcontrolid="Button1" popupcontrolid="DivDeleteConfirmation" backgroundcssclass="ModalPopupBG" />
       <asp:confirmbuttonextender id="Confirmbuttonextender1" runat="server" targetcontrolid="Button1" enabled="True" displaymodalpopupid="Modalpopupextender1" />                            

Is there anyone who has seen the same thing? Is it a bug? and most important is there a whay I can solve this?

Thx for any reply :)




This is an old post but I’m having a similar problem, so if you or anybody can provide some explanation or help I would appreciate.

I’m using a ListView and UpdateProgress works fine but if I define QueryStringField property in DataPager the updateProgress stops showing?! I wonder if it is a bug or if it get’s disabled for any reason.


You can refer this to show ModalPopup as an AJAX Progress Indicator


[RESOLVED]imagebutton commandname in listview not respond

<asp:UpdatePanel ID="UpdatePanel3" runat="server">

        <div class="slip-background">
            <asp:ListView ID="ListView1"  runat="server" DataKeyNames="Stake, StakeSum" OnItemDataBound="ListView1Slip_ItemDataBound"  OnItemCommand="ListView1_ItemCommand" >
                    <div class="slipbet-data">
                        <div style="float:left; margin-left:-4px; margin-top:2px;"><asp:Image ID="Image1" runat="server" ImageUrl="~/images/datetime-icon.png" ImageAlign="AbsBottom" ToolTip='<%# Eval("DateOfEvent") %>'  /></div><div style="margin-left:15px;"><asp:Label ID="lblNameOfEventLabel" runat="server" Text='<%# Eval("NameOfEvent") %>'></asp:Label></div>
                        <asp:ImageButton ID="ImageButton1" CommandName="DeleteEvent" AlternateText="2" runat="server" />
                        <div style="margin-left:15px;"><asp:Label ID="lblTypeOfBets" runat="server" Text='<%# Eval("TypeOfBets") %>'></asp:Label></div>
                        <div style="float:left; margin-left:15px;"><asp:Label ID="lblPickLabel" runat="server" Font-Bold="true" Text="Pick:"> </asp:Label> <asp:Label ID="lblPick" runat="server" Font-Bold="true" Text='<%# Eval("Pick") %>'></asp:Label></div>
                        <div style="float:right"><asp:Label ID="lblOddsLabel" runat="server" Text='<%# Eval("Odds") %>'></asp:Label></div><br />
                        <div id="DivStake" runat="server">
                        <div style="float:left;margin-left:15px; margin-top:2px;">Stake <asp:TextBox ID="txtStake" Text='<%# (Convert.ToString(Eval("Stake"))) == "" ? "0.00" : Eval("Stake") %>'  runat="server" class="staketext" Height="12px" Width="50px" ></asp:TextBox></div>
                        <div style="float:right;"><asp:Label ID="lblStake" class="stake" Text='<%# (Convert.ToString(Eval("StakeSum"))) == "" ? "0.00" : Eval("StakeSum") %>'  runat="server" ></asp:Label></div><br /></div>
                <EmptyDataTemplate>No bet has been selected. To select a new bet, please click on the respective odds.</EmptyDataTemplate>

    protected void ListView1_ItemCommand(object source, ListViewCommandEventArgs e)
        if (e.CommandName == "DeleteEvent")
         /*   ListViewItem item = ((Control)e.CommandSource).NamingContainer as ListViewItem;

            string EventDelete = ListView1.DataKeys[item.DataItemIndex].ToString();

            Session["DelId"] = EventDelete;





What is problem with my example?


Maybe you have to refill the ListView on each PostBack.

Here are some similar threads, please try to refer to:

http://stackoverflow.com/questions/11992450/asp-net-editing-item-from-listview-using-an-imagebutton .

http://stackoverflow.com/questions/5329002/imagebutton-within-listview-problem .

Hope it helps.

Best Regards,
Amy Peng

[RESOLVED]No overload for 'ListView1_ItemCommand'

<asp:ListView ID="ListView1"  runat="server" DataKeyNames="Stake, StakeSum" OnItemDataBound="ListView1Slip_ItemDataBound" OnItemCommand="ListView1_ItemCommand" >

returns No overload for ‘ListView1_ItemCommand’ .

I need to use Command events because I have                    <asp:ImageButton ID="ImageButton1" CommandName="DeleteEvent" runat="server" /> and I want to call DeleteEvent function.

Please help.


You have post a same question in:

http://forums.asp.net/t/1922224.aspx .

Please try to check it.

Best Regards,
Amy Peng