Posts Tagged ‘ListView’

Posted by OmegaMan at June 8, 2009

Category: ASP.Net, Controls, Tribal Knowledge

Tags: , ,


This article discusses the use of the attribute DataKeyNames of the ListView which can hold individual IDs for each row and how when using a CheckBox and processing an individual click, to get that info during the OnChange event. That ID is not directly supplied to the OnChange event as easily as done when directly working with ListView events. That ID, specific to the actual data is needed so an can update  of status can be sent to the target database item which it represents.


In setting up the ListView’s HTML I provide a quick example from a previous article here (Quick Asp.Net ListView Template). The item to take out of it is the property DataKeyNames.  For this article I have a Nationalities (USA, France, Argentina…) table which has two boolean fields of Archive and Exempt which are represented as checkboxes within each row of the ListView. The ListView will know that each row’s ID maps to the column NatID field which is the primary key id of the data item. Here is the html which specifies “NatID” as the id column in the data during the databind:

<asp:ListView ID="lvNationalities"

In the code behind my dynamic Linq entity looks like this and the dynamic entity contains a NatID which is the items primary key id and it has our properties for the checkbox states for archived and exempt.

var natgeos = from nat in _gtdc.Nationalities
              select new
                  NatID    = nat.Nationality_ID,
                  Archived = nat.Archived,
                  Exempt   = nat.Exempt,
                  Name     = nat.Text

lvNationalities.DataSource = natgeos;

So NatID is pulled from the database item as shown above. Visually we will have to CheckBoxes for Archived and Exempt as mentioned for the user to change. Each change needs to be handled by the checkbox and the database immediately updated.  Here is a screen shot:



Below is the code which specifies the specific CheckBox event. Looking at the archive CheckBox we handle an OnCheckedChanged event:

<asp:CheckBox ID="cbArchived"
              Checked='<%# Eval("Archived") %>'

Because we are not using the command methodology of the ListView, when we handle the event of the checkbox we don’t have direct access to which row data has been checked. To do that we will dereference some items which will get us to the NatID of row item which was clicked. Here is the code to do that:

protected void ArchiveChanged( object sender, EventArgs e )

CheckBox target = sender as CheckBox;

if ( target != null )
    ListViewDataItem di = target.NamingContainer as ListViewDataItem;

    if ( di != null )
        int id = (int)lvNationalities.DataKeys[di.DataItemIndex]["NatID"];

        _gtdc = new GTCDataContext( Utilities.GetConnectionString() );

        var item = _gtdc.Nationalities.Where( it => it.Nationality_ID == id ).FirstOrDefault();

        if ( item != null )
            item.Archived = target.Checked;


The first step is to convert the sender object to a CheckBox. Once that is successful we use the NamingContainer property off of the CheckBox. That property allows us to access the parent item which is the ListViewDataItem. That is our link back to the ListView. With that we can divine the ID needed from the ListViewDataItem’s index into the DataKeys cache for that row’s ID. Once gotten we can update the database as shown by setting the Archive attribute for the Nationalities for the user selected item.


Posted by OmegaMan at June 7, 2009

Category: ASP.Net, Controls

Tags: ,

I find that I seem to make the same Asp.Net ListView and internal table html code over and over. The below code contains that table where each row of data corresponds will be bound to each row of data in a database. Here is that template with blank values which will need to be filled in:

<asp:ListView ID="lvXXXXX"              
        <table class="">        
                    <th>Header 1</th>            
                <asp:PlaceHolder runat="server" ID="PlaceHolder1" />
            <td><asp:Label ID="lblYYYY"                
                     Text='<%# Eval("") %>'/>        

Posted by OmegaMan at October 2, 2008

Category: ASP.Net

Tags: , , ,

(Update 03.28.2012 Cleaned up article and verified it  works with versions 3.5 and 4.0)

The following ASP.Net article details how to create a ListView, bind it to a Linq query and create a dynamic list of hyperlinks to show on an web page in C#. To recreate this, use Visual Studio (VS2008/VS2010/VS 11) and create a default Asp.Net Web Application project all working in the default page setup.

On the screen there will be a button which will cause a refresh to the page when pressed. On that refresh the ListView will be cleared of all data and the button disabled to show that the control has not been rebound to actual data.

Here is what it will look like on its first run with a button and dynamically created html links in a list.

Example showing button and dynamic links

HTML: which has the button and the ListView. We will hand create the LayoutTemplate and the ItemTemplate. Our goal is to have a list of links and dynamically create them. The ItemTemplate is expecting to be bound to Url field and UrlText which Linq will nicely create for us in the code behind.

<asp:Button ID="btnClear" runat="server" Text="Clear" /> 

<br /> 
<asp:ListView ID="lvPanelGroup1" runat="server">     
                <asp:PlaceHolder runat="server" ID="itemPlaceholder" />             
            <asp:HyperLink ID="HyperLink1"                            
                           NavigateUrl='<%# Eval("Url") %>'                            
                <%# Eval("UrlText") %>

C#:The following is the code in the PageLoad. Its job is to either bind the data in the ListView using Linq or clear the ListView of all items and disable the control. Notice the Linq code where we create our object to have a Url field and UrlTextField which the ListView will use.

protected void Page_Load(object sender, EventArgs e) 
    if (IsPostBack == false) 
        List<string> Titles = new List<string>()        
            { "Title 1", "Title 2", "Title 3", "Fini"};     

        int index = 0;     

        var links = from item in Titles                 
                    select new                 
                                Url = "~Default.aspx?articleid=" + (++index).ToString(),                     
                                UrlText = item                 
        lvPanelGroup1.DataSource = links;     
        btnClear.Enabled = true; 
    else // Clear the ListView 
        lvPanelGroup1.DataSource = null;     

        // The rebinding will clear the ListView.     
        btnClear.Enabled = false; 

Here is what happens after a button press:

What happens after Clear is pressed.

Hope this helps those learning about the ListView and Linq.

  • Recent Comments

    Thanks for this simple yet delightful code....
    Hey guys I'm having the same problem as Netanel KL { “Error HRESUL...
    Soluciono el problema con el primero (First step solved it for me)....
    Thank you! I was looking for this. You save my day!...
    Thank you! This was a big help. My requirement was a little differen...
    Thanks, after a small path adjustment it worked for Visual Studio 2015...
    Good call!...
    Thank you .. this helped...
    How about when you have a long string with no space? I tried it and it...
    Thank you, I ran into this same issues with Visual Studio 2015 after i...