Archive for category ASP.Net

Problems One May Encounter When trying to use the Ajax Control Toolkit for the first time.

Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure “AjaxControlToolkit.Properties.Resources.resources” was correctly embedded or linked into assembly “AjaxControlToolkit” at compile time, or that all the satellite assemblies required are loadable and fully signed.

System.Resources.MissingManifestResourceException: Could not find any resources appropriate for the specified culture or the neutral culture.  Make sure “AjaxControlToolkit.Properties.Resources.resources” was correctly embedded or linked into assembly “AjaxControlToolkit” at compile time, or that all the satellite assemblies required are loadable and fully signed.

AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the AjaxScriptManager in System.Web.Ajax.dll, or use the ToolkitScriptManager in AjaxControlToolkit.dll.

The latest incarnation (3.6.097 as of this writing) of the asp.net Ajax Control Toolkit needs to be setup using its script manager and not the standard asp.net Script Manager.

So one way to avoid the above issues is to drag the ToolkitScriptManager (found in the control toolkit) onto the Form tag and then use any other Ajax Controls. Here is an example of it using the TabContainer:

<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager2" runat="server"/>
<div>
    <asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="1">
        <asp:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel1">
            <ContentTemplate><p>Hello</p></ContentTemplate>
        </asp:TabPanel>
        <asp:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2">
        <ContentTemplate><p>Hello2</p></ContentTemplate>
     </asp:TabPanel>
    </asp:TabContainer>
</div>
</form>
  • Share/Bookmark

Tags:

Asp.Net C# Creating an Excel Document From Data without using Office Interops

Excel It is a common misconception that one needs the office interops to create Excel documents for the user to download when dealing with Asp.net on a server. Well this article shows one how to create an Excel document from just the data at hand, say from Linq entities, without being tied to any control nor having to use office interops!

How Does one Send the Data to the User?

Here is the shell which will encompass the code which creates the document. Basically one uses the response class to send the data back to the user, say on a button click or some other relevant event. By specifying that this object will be a ms-excel file and it has an .xls extension, that is half the battle right there.

Response.Clear();
Response.Buffer      = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader( "Content-Disposition", "attachment;filename=registrationData.xls" );
this.EnableViewState = false;

//  Code here to generate the xls document.
...

HttpContext.Current.Response.Write( /* String Buffer to Here */ );
HttpContext.Current.Response.End();

That was pretty easy to send the information to the user using a few C# classes which are globally exposed to the code-behind of our web page.

Generate an Excel document from Data in C#

Our goal is not to be tied to any control on the web page, though some controls such as the GridView have the ability to easily export a table which can be passed on. But for our purposes we want to simply extract the data from a linq query and generate the document. By keeping this example generic, one can adapt it to many different situations.

// We will be creating html on the fly via the
// string and html writers to create a table on the fly.
using ( StringWriter sw = new StringWriter() )
    using ( HtmlTextWriter htw = new HtmlTextWriter( sw ) )
    {
        //  Create a table to contain the grid
        Table table = new Table();

        //  Gridlines to box the cells
        table.GridLines = System.Web.UI.WebControls.GridLines.Both;

        // We are going to add the header row to the data first.
        List columns = new List() {
        "Sent", "Sent Date", "User Name", "Last Name", "First Name",
        "Work Phone", "Work Email",    "Number of Tickets", "Street Address 1",
        "Street Address 2",    "City", "State", "Zip Code" };

        // Each row will need to be declared upfront and cells added later.
        TableRow tRow = new TableRow();
        string value;

        foreach ( string name in columns )
            tRow.Cells.Add( new TableCell() { Text = name } );

        table.Rows.Add( tRow ); // Done! Header row added.

        // Note TableCell has a property BackColor. Once can set the
        // that within the cell such as BackColor = System.Drawing.Color.Blue
        // and that will carry into the Excel Document!

        // UserData is our Linq entity list and we will enumerate it to fill the into cells of the row
        // and subsequently into the table.
        foreach ( var usr in UserData )
        {
            tRow = new TableRow();

            value = ( usr.ticketsSent == null ) ? "N" : usr.ticketsSent.Value.ToString();
            tRow.Cells.Add( new TableCell() { Text = value } );

            value = ( usr.ticketsSentDate == null ) ? string.Empty : usr.ticketsSentDate.Value.ToShortDateString();

            tRow.Cells.Add( new TableCell() { Text = value } );
            tRow.Cells.Add( new TableCell() { Text = usr.userName } );
            tRow.Cells.Add( new TableCell() { Text = usr.lastName } );
            tRow.Cells.Add( new TableCell() { Text = usr.firstName } );
            tRow.Cells.Add( new TableCell() { Text = usr.workNumber } );
            tRow.Cells.Add( new TableCell() { Text = usr.workEmail } );
            tRow.Cells.Add( new TableCell() { Text = usr.ticketsRequested.Value.ToString() } );
            tRow.Cells.Add( new TableCell() { Text = usr.address1 } );
            tRow.Cells.Add( new TableCell() { Text = usr.address2 } );
            tRow.Cells.Add( new TableCell() { Text = usr.city } );
            tRow.Cells.Add( new TableCell() { Text = usr.state } );
            tRow.Cells.Add( new TableCell() { Text = usr.zipCode } );

            table.Rows.Add( tRow ); // We add each row to the table.
        }

        //  Translate/Render the table into the htmlwriter
        table.RenderControl( htw );

        //  Response needs the Htmlwriter
        HttpContext.Current.Response.Write( sw.ToString() );
        HttpContext.Current.Response.End();
       }

By simply creating a mock table we can load it and ship it out to the user as an automatic download.

Full Code

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader( "Content-Disposition", "attachment;filename=registrationData.xls" );
this.EnableViewState = false;

using ( StringWriter sw = new StringWriter() )
    using ( HtmlTextWriter htw = new HtmlTextWriter( sw ) )
    {
        //  Create a table to contain the grid
        Table table = new Table();

        //  Gridline to box the cells
        table.GridLines = System.Web.UI.WebControls.GridLines.Both;

        List columns = new List() {
        "Sent", "Sent Date", "User Name", "Last Name", "First Name",
        "Work Phone", "Work Email",    "Number of Tickets", "Street Address 1",
        "Street Address 2",    "City", "State", "Zip Code" };

        TableRow tRow = new TableRow();
        string value;

        foreach ( string name in columns )
            tRow.Cells.Add( new TableCell() { Text = name } );

        table.Rows.Add( tRow );

        // BackColor = System.Drawing.Color.Blue
        foreach ( var usr in UserData )
        {
            tRow = new TableRow();

            value = ( usr.ticketsSent == null ) ? "N" : usr.ticketsSent.Value.ToString();
            tRow.Cells.Add( new TableCell() { Text = value } );

            value = ( usr.ticketsSentDate == null ) ? string.Empty : usr.ticketsSentDate.Value.ToShortDateString();

            tRow.Cells.Add( new TableCell() { Text = value } );
            tRow.Cells.Add( new TableCell() { Text = usr.userName } );
            tRow.Cells.Add( new TableCell() { Text = usr.lastName } );
            tRow.Cells.Add( new TableCell() { Text = usr.firstName } );
            tRow.Cells.Add( new TableCell() { Text = usr.workNumber } );
            tRow.Cells.Add( new TableCell() { Text = usr.workEmail } );
            tRow.Cells.Add( new TableCell() { Text = usr.ticketsRequested.Value.ToString() } );
            tRow.Cells.Add( new TableCell() { Text = usr.address1 } );
            tRow.Cells.Add( new TableCell() { Text = usr.address2 } );
            tRow.Cells.Add( new TableCell() { Text = usr.city } );
            tRow.Cells.Add( new TableCell() { Text = usr.state } );
            tRow.Cells.Add( new TableCell() { Text = usr.zipCode } );

            table.Rows.Add( tRow );
        }

        //  Htmlwriter into the table
        table.RenderControl( htw );

        //  Htmlwriter into the response
        HttpContext.Current.Response.Write( sw.ToString() );
        HttpContext.Current.Response.End();
   }
  • Share/Bookmark

Tags: ,

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

Tags: , ,

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

Tags: ,

Asp.Net DropDownList bound with Linq Data Example

I recently answered a post where the user was using ASP .Net 3.5 but not binding data to a DropDownList but instead using hard coded data to load the drop down in the HTML. So I created this quick example to show Linq-To-Xml (Linq) loading of an Asp.Net DropDownList and handling the automatic postback selection changes.

As mentioned example shows how to bind data to a dropdown list using Linq, specifically Linq-To-Xml, but you could use any other of the Linq methodologies because we are using the anonymous types to work with the needs of the DropDownList.

First we will place the Asp.Net DropDownListon our page along with a label which will used to show state changes.

<asp:DropDownList ID="ddlMain"
      runat="server"
      AutoPostBack="true"
      OnSelectedIndexChanged="SelectionMade" />

<asp:Label ID="lblWhat" runat="server"/>

Nothing earth shattering here, we have AutoPostBack because we want the control to tell our code behind on the server when a selection has been made. Following that we have the method which will be called for that event of SelectionMade.

The next thing is to load the DropDownList with values to choose from. We will use an XElement loaded dynamically to show how to do do this in Linq. The other thing of note is that we only want load this once, so we check the postback status. If its a postback, we do not reload.

protected void Page_Load( object sender, EventArgs e )
{

if ( Page.IsPostBack == false ) // Only do this once
{
   // Simulate an Linq-To-SQL call with an Linq-To-SQL
   // So anyone can use this demo.
   XElement dataForList
       = new XElement(
           "DropDownData",
             new XElement( "Node",
                 new XElement( "Text", "Selection 1"  ),
                 new XElement( "Data", "1Selection" ) ),
             new XElement( "Node",
                 new XElement( "Text", "Selection 2" ),
                 new XElement( "Data", "2Selection"  ) ));

   var toTheScreen = from x in dataForList.Descendants( "Node" )
                 select new
                 {
                     Text = x.Descendants( "Text" ).First().Value,
                     Value = x.Descendants( "Data" ).First().Value
                 };

    ddlMain.DataTextField = "Text";
    ddlMain.DataValueField = "Value";
    ddlMain.DataSource = toTheScreen;
    ddlMain.DataBind();
}

}

As shown above we work through all the elements named Node. For each of those nodes we will create a new entity with two properties Text and Value. Text will be shown to the user and value is what is associated with the selection. In the binding operations we specify the Text and Value field for the DropDownList to use and simply bind it to our anonymous projection.

Now all we have to do is handle the selection change event

protected void SelectionMade( object sender, EventArgs e )
{
    DropDownList target = sender as DropDownList;

    if ( target != null )
        lblWhat.Text =
            string.Format(
                "Item {0} selected with Value of {1}",
                target.SelectedItem.Text,
                target.SelectedValue );
}

Nothing magical here, we get the DropDownList from the sender argument, divine the selection and update the label. Here is what it should look like after a change:

ddl

  • Share/Bookmark

Tags: , , ,

C# Ajax Control Toolkit CascadingDropDown Step By Step

This breaks down step by step what to do to create a cascading drop down using the Ajax Control toolkit in C# and Asp.net 3.5.

  1. Create a web service outside the html page. Decorate the class with the below attribute
  2. // To allow this Web Service to be called from script,
    // using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class AjaxServices : System.Web.Services.WebService
    { ... }
  3. Now create a webmethod with any name. Note if the webmethod resides on the same page (a page level service method) as your html page, make it a static method. But normally if you are creating an asmx web page, do not make it static.  This example is not creating a page level service method.

    The return is a CascadingDropDownNameValue [] type which is found in the ajax toolkit. The parameters of the webservice method has to be as

    string knownCategoryValues
    string category
    .

    Those parameters have to be in that case and format; do anything else and a general ajax failure will occur when ajax calls the method. The below shows a Linq db call returning the proper object, and handling the category and the value which will be sent. See the notes in the code about what ajax actually sends. .

  4. [WebMethod]
    public CascadingDropDownNameValue[] GetExportTypes   ( string knownCategoryValues, string category )
    {
    
    GTCDataContext gtdc       = new GTCDataContext( Utilities.GetConnectionString() );
    IEnumerable<CascadingDropDownNameValue> vals = null;
    int targetID = 0;
    
    // The data comes in as "XXXX:1" where XXXX is the originating
    // control category, which is *not* the same as the category.
    // The 1st control will pass in nothing (empty) for the
    // knownCategory while 2+ control will pass in
    // the originating category and its ID with a :.// Remove the XXXX: and extract an integer value.
    if (string.IsNullOrEmpty( knownCategoryValues ) == false)
        int.TryParse(
            Regex.Match( knownCategoryValues,
                         @"(\d+)",
                         RegexOptions.Compiled).Groups[0].Value,
                         out targetID);
    
    switch ( category )
    {
        case "Type" : // 1st Initiating DropDownList
            vals = from tp in gtdc.Type_Exports
                   select new CascadingDropDownNameValue
                   {
                       name = tp.Text,
                       value = tp.Export_Type_ID.ToString(),
                   };
            break;
    
        case "SubType": // Next/child DropDownList
            vals = from tp in gtdc.Type_Export_SubTypes
                   where tp.ID_Type_Export == targetID
                   select new CascadingDropDownNameValue
                   {
                       name = tp.Text,
                       value = "0",
                   };
    
            break;
    }
    
    return vals.ToArray<CascadingDropDownNameValue>();
    
    }
  5. Test your webservice before trying to hook it up! Very important.
  6. Add an ajax ScriptManager  to the target html page.
  7. Add an ajax UpdatePanel to the page.
  8. Within the panel add the DropDownLists, two in this example.
  9. Add a CascadingDropDown control extender to the page for each dropdownlist which will be used. Set the TargetControlID to the id of desired dropdown to work with.
  10. <asp:DropDownList ID="DropDownList1" runat="server" />
    <cc1:CascadingDropDown ID="CascadingDropDown1"
                           runat="server"
                           Category="Type"
                           TargetControlID="DropDownList1"
                           LoadingText="Acquiring ..."
                           PromptText="Select Type Of Export"
                           ServiceMethod="GetExportTypes"
                           ServicePath="~/AjaxServices.asmx"
    
                           >
    </cc1:CascadingDropDown>
    
    <asp:DropDownList ID="DropDownList2"
                      runat="server"
                      AutoPostBack="false">
    </asp:DropDownList>
    <cc1:CascadingDropDown ID="CascadingDropDown2"
                           runat="server"
                           Category="SubType"
                           TargetControlID="DropDownList2"
                           ParentControlID="DropDownList1"
                           LoadingText="Acquiring ..."
                           PromptText="Select End Use"
                           ServiceMethod="GetExportTypes"
                           ServicePath="~/AjaxServices.asmx"
    
                           >
    </cc1:CascadingDropDown>
  11. If your last drop down is doing a postback on the page tag turn off event validation or a postback javascript error will be thrown. (The above example has AutoPostBack turned off so no need to do step 7).

    EnableEventValidation=”false”

  12.  
     
     
  • Share/Bookmark

Tags: ,

ASP.NET Ajax C# Example: AutoCompleteExtender With Progress Indicator

Waiting

This article demonstrates in a step by step fashion how to use the Ajax Control Toolkit’s AutoCompleteExtender control with an animated gif ajax-loader progress indicator while the target dropdown of the AutoCompleteExtender is waiting to be loaded.

This article relies on the fact that you, the developer, already have the toolkit loaded and that a medium level of knowledge of Asp.net, C# and Visual Studio operations are understood. This targets VS2008 SP1, .Net/Asp.net 3.5 SP1,  Ajax Control Toolkit 3.0.20820.

Steps

  1. Create the  animated GIF which will be used. Go to the site AjaxLoad.Infowhere one can create animated loading gifs and download them for free. Use firefox to view the site because one can see the types of icons in the dropdown, on the site, where IE does not. Once done save your the icon to your project.
  2. The Ajax extender will need to call a webservice to get the data. Create a webservice (.asmx oldstyle type), in this example named AjaxServices.asmx. Within that service add, or uncomment out,  the following attribute declaration to allow the service to have communication from the page to the service in a scriptable manner.
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class AjaxServices : System.Web.Services.WebService
    {
  3. Create a web method, the actual method name can be anything, but it must have the exact input parameters and return value as shown below. Note we introduce a delay for this demonstration effect (highlighted line) you will not need to do that. Right. :-)  
    [WebMethod]
    public string[] GetUsers( string prefixText, int count )
    {
        List<string> names
       = new List<string>()
        { "Alpha", "Beta", "Gamma", "Delta", "Omega" };
    
        // Fake delay to see the update gif
        System.Threading.Thread.Sleep( 5000 );
    
        return names.ToArray();
    }
  4. On the web page where the controls will be, add the asp:ScriptManager control. Within the manager we need to let it know our web service we have created and it will be using.
    <asp:ScriptManager ID="ScriptManager1"
        runat="server"
        EnablePartialRendering="true">
    
     <Services>
       <asp:ServiceReference Path="~/AjaxServices.asmx" />
     </Services>
    
    </asp:ScriptManager>
  5. Add three more controls, an asp.net textbox  the autoCompleteExtender and the image gif. Here are the controls all added. Note how the extender references the webservice and webmethod, the textbox and calls a javascript function which we will show in step 6. Change the MinimumPrefixLength to two or three if the data list is quite huge. in your system. 
    <table>
    <tr>
        <td>User:&nbsp;&nbsp;</td>
        <td><asp:TextBox ID="tbUser" runat="server"></asp:TextBox></td>
        <td>&nbsp;</td>
        <td><img id="processing" style="visibility:hidden" src="ajax-loader.gif" /></td>
        <td>&nbsp;</td>
        <td><cc1:AutoCompleteExtender
       ID="AutoCompleteExtender1"
       runat="server"
       TargetControlID="tbUser"
       ServicePath="AjaxServices.asmx"
       ServiceMethod="GetUsers"
       MinimumPrefixLength="1"
       EnableCaching="true"
       CompletionSetCount="25"
       onclientpopulating="ShowIcon"
       onclientpopulated="ShowIcon"/>
        </td>
    </tr>
    </table> 
  6. The image starts off hidden. We will write a javascript method, to swap its state.  Place the code on the page after the <Head> section. The code has to know the name of the img tag. The code should look like this:
<script language ="javascript">

function ShowIcon() {

    var e = document.getElementById("processing");

    e.style.visibility =  (e.style.visibility == 'visible') ? 'hidden' : 'visible';

}

</script>

That is it! When done and the extender calls the webservice the gif gets displayed and the user knows something is happening. When the processing is done the same javascript method is called to turn it off.

Note: If no data is found, the final hook call to onclientpopulated is not done and the icon will still be displayed. Possibly you can send back text like “No data found”, but that will be populated in the textbox and has its drawbacks. That is the monkey’s paw wish caveat of using this methodology.

  • Share/Bookmark

Tags: , , , ,

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

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) 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/Bookmark

Tags: , , ,

OmegaMan's Musings is Digg proof thanks to caching by WP Super Cache