Posts tagged ‘ListView’

Tribal Knowledge: Asp.net ListView Template Which Contains a CheckBox. How to Get an ID from its OnChange Event in C#

TribalKnowledge

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.

Setup

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"
              DataKeyNames="NatID"
              runat="server"
              OnPagePropertiesChanged="UpdateNationalities"
              ItemPlaceholderID="PlaceHolder1">

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;
lvNationalities.DataBind();

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:

NationalitiesListView

CheckBox

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

<asp:CheckBox ID="cbArchived"
              runat="server"
              AutoPostBack="true"
              Checked='<%# Eval("Archived") %>'
              OnCheckedChanged="ArchiveChanged"
              Text="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;
            _gtdc.SubmitChanges();
        }
    }
}

}

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.

Share

Quick Asp.Net ListView Template

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"              
              DataKeyNames=""              
              runat="server"              
              ItemPlaceholderID="PlaceHolder1">
    <LayoutTemplate>    
        <table class="">        
            <thead>            
                <tr>                
                    <th>Header 1</th>            
                </tr>        
            </thead>        
            <tbody>
                <asp:PlaceHolder runat="server" ID="PlaceHolder1" />
            </tbody>    
        </table>
    </LayoutTemplate>
    <ItemTemplate>    
        <tr>        
            <td><asp:Label ID="lblYYYY"                
                     runat="server"                
                     Text='<%# Eval("") %>'/>        
            </td>    
        </tr>
    </ItemTemplate>
</asp:ListView>
Share

Asp.Net ListView: Linq Allows Creation of Dynamic Hyperlinks Example

(Update 03.28.2012 Cleaned up article and verified it  works with Asp.net 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 Asp.net 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">     
    <LayoutTemplate>         
        <div>             
            <ul>                 
                <asp:PlaceHolder runat="server" ID="itemPlaceholder" />             
            </ul>         
        </div>     
    </LayoutTemplate>     
    <ItemTemplate>         
        <li>             
            <asp:HyperLink ID="HyperLink1"                            
                           NavigateUrl='<%# Eval("Url") %>'                            
                           runat="server">
                <%# Eval("UrlText") %>
            </asp:HyperLink>         
        </li>     
    </ItemTemplate> 
</asp:ListView>

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;     
        lvPanelGroup1.DataBind();     
        btnClear.Enabled = true; 
    } 
    else // Clear the ListView 
    {     
        lvPanelGroup1.Items.Clear();     
        lvPanelGroup1.DataSource = null;     
        lvPanelGroup1.DataBind(); 

        // 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.

Share