ASP.NET 4 ClientIDMode Property Explained

   Posted by: Jim Rouse

There has been some confusion about how to work with this property to your advantage.  With out being to long winded I hope to provide some clarity.

When to change the ClientIDMode of a control?

...if you need to locate specific controls that exist in a repeating data control without capturing events from that control which you are try to reference.  This commonly occurs when you are trying to coordinate user actions to html objects using JavaScript.  

First lets look at the possible values for this property:

AutoID Process used in previous versions ASP.NET  which was prefixing an incrementing value to the control ID
Static Client ID value is set to the value of the ID property
Predictable

Basic Algorithm is either of the following
[parent clientid] + "_" + [ClientIDRowSuffix]
or

[parent clientid] + "_" + incrementing value

Inherit Control inherits the setting of its parent control

For a complete description visit ClientIDMode On MSDN

To demonstrate the affects of each of the property values and how the generated client side ID is affected I will create an web page with several controls:

  1. Using VS 2010 File menu create a new ASP.NET Empty Web Application.
  2. Add a new Web Form
  3. Open the web form
  4. In design view drag and drop two Grid Views onto the design surface making sure they are contained in the default div tag that was provided by the designer.
  5. For both GridViews set the AutoGenerateColumns="false"
  6. We now have two unexciting GridViews that need some data.  Add a new class to the solution.  Name Product and give it two properties (feel free to use the following)
       1: public class Product
       2: {
       3:    public string ProductID{get;set;}
       4:    public string ProductName{get;set;}
       5: }
  7. Open the code behind file for the Web page, for me it is named WebForm1.aspx.cs for me
  8. Create a new method that will be used to populate our GridViews with a list of Products.  (see following code).
       1: protected void Page_Load(object sender, EventArgs e)
       2: {
       3:     LoadProductsToGrids();
       4: }
       5:  
       6: private void LoadProductsToGrids()
       7: {
       8:     List<Product> productList = new List<Product>
       9:     {
      10:         new Product{ProductID="A026",ProductName="Apples"},
      11:         new Product{ProductID="B146",ProductName="Bananas"},
      12:         new Product{ProductID="C276",ProductName="Chiote"},
      13:         new Product{ProductID="D356",ProductName="Drumsticks"},
      14:         new Product{ProductID="E486",ProductName="Elephant Ears"},
      15:         new Product{ProductID="F556",ProductName="Fries"},
      16:         new Product{ProductID="G656",ProductName="Green beans"},
      17:         new Product{ProductID="H756",ProductName="Hay"},
      18:         new Product{ProductID="I856",ProductName="Idaho Potatoes"}
      19:     };
      20:     GridView1.DataSource = productList;
      21:     GridView2.DataSource = productList;
      22:     GridView1.DataBind();
      23:     GridView2.DataBind();
      24: }
  9. To display this data on our web page I will use templated fields because it will easily allow me to demonstrate the affects of the ClientIDMod property.
  10. Open the web page and view the HTML source and add the following templated fields to both of the GridViews
       1: <Columns>
       2:     <asp:TemplateField>
       3:         <HeaderTemplate>Product ID</HeaderTemplate>
       4:         <ItemTemplate ><asp:Label ID="ProductID" runat="server" Text='<%# Bind("ProductID") %>'></asp:Label></ItemTemplate>
       5:     </asp:TemplateField>
       6:     <asp:TemplateField>
       7:         <HeaderTemplate>Product Name</HeaderTemplate>
       8:         <ItemTemplate ><asp:Label ID="ProductName" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label></ItemTemplate>
       9:     </asp:TemplateField>
      10: </Columns>
  11. Now before we run code for two labels contained in the second "GridView2" set the the ClientIDMode to "AutoID"
  12. [Example #1] Running the application you will see two identical grids, but viewing the page source will reveal:
    1. The top grid with the label controls using the default ClientIDMode of Inherit have the control naming pattern ParentContainerID_LabelID_IncrementingValue
    2. The bottom grid with label controls using the default ClientIDMode of AutoID have the control naming patter that was used in prior ASP.NET versions ParentContainerID_ctl+incrementingvalue_IncrementingValue
    3. Inherit_vs_AutoID
  13. [Example#2] Lets change the labels contained in GridView1 to have the ClientIDMode = "Predictable"; Then change the labels in GridView2 to have the ClientIDMode = "Static"
  14. Running the application you will see the following results
    1. The ClientIDMode = "Predictable" behaves as we had seen with the Inherit setting but be careful Inherit will take on its parent setting and could cause some unexpected results when your controls are inside a container such as a Master Page.  So be sure to set your ClientIDMode to predictable if you have dependencies on the control name being ....well...'predictable'
    2. The value of Static, is just like it sounds, this property value causes all iterations of the control to be named the same "ProductID" and "ProductName" respectively.  Regardless of what we do to the containing GridView the labels will continue to repeat the same name.
    3. Predictable_vs_Static
  15. [Example#3] Now we've seen the variations of the ClientIDMode property to see the true value of the property we need to use the ClientIDRowSuffix property that is available to us on the GridView (and some other controls).
    1. On GridView1 set the ClientIDRowSuffix = "ProductID"
    2. On GridView2 set the ClientIDRowSuffix = "ProductID" and ClientIDMode = "Static"
    3. For the labels contained in GridView2 set the ClientIDMode = Predictable
  16. Running the application you will see the following pattern:
    1. For the label controls contained in GridView1 the label IDs have the following pattern: ParentContainerID_LabelID_ProductID
    2. For the controls contained in GridView2 the label IDs have the following pattern: LabelID_ProductID
    3. ClientIDRowSuffix

So you can see that using the ClientIDRowSuffix along with the ClientIDMode you can establish a control ID naming pattern that should support the majority of your needs.

Visual Studio 2010 C# Project Source (ClientIDMode Example)

~Enjoy~

ASP.NET Chart Drill Down

   Posted by: Jim Rouse

In this example we will extend the previous pie chart to be a drill down chart, so all of the code and data will be utilizing what had been previously created.  Please feel free to start with code from previous blog (Create ASP.NET 4.0 Pie Chart with Tooltips). 

What are we creating?

A drill down chart is an interactive chart that has clickable or interactive hot spots that will allow us to view more specific information for user selected data. Continuing with our retail theme from the first blog: A department level manager, having been impressed with your pie chart, would like to have a line graph be displayed with more specific sales information for the selected product category.


A moment on User Interface Design

Before we start coding it's important to think about how our application is being used; yes what is the workflow of our targeted end users, will they typically use the mouse or keyboard to navigate within our application. In this case we are being requested to provide a line graph based on a selected value. We do have options to accomplish this task, and depending on the typical workflow of our end users we can quickly determine which option is right for your application.

Two simple options to accomplish this task would be:

1. Use a drop down list control that would allow the user to select the department from the list; great for those who primarily use the keyboard for application navigation (think data entry).

2. Pie graph interactivity, creating clickable graph hot spots allowing the user to click the desired product category and display the corresponding data.

Given the title of this blog you know that I will be using the second option but it is important to know there are several reasons why I would choose the section option.

1. Today's users are expecting more interactivity from their business applications, this includes graphs.

2. In this example, the manager assures me that users will primarily be using a mouse for navigation as these charts will be hosted inside an internal Share Point site.

3. So for the 'mouse-navigators' of the world this means that by using drill-down functionality (as compared to the drop down) will require one less mouse-click for the user to accomplish their desired response (seeing the detailed data). (Alternatively, if my users were primarily using the keyboard for navigation then I most likely wouldn't use a graph drill down for navigation.)


Lets start coding (Extend the existing pie chart)

First we need to extend the existing pie chart to provide data and the event that will allow us to respond to the user's request. An item to note is that utilizing multiple series for a single chart is very helpful in supporting your business rules and typically the easiest option to reference corresponding data values after your graph has been data bound.

  1. Set the PostBackValue for Series1
    • Open the Series Collection Editor by selecting the Pie Chart and clicking the ellipsis for the Series propertySeries Property
    • Select Series1 in the Members panel
    • In the properties panel scroll down and expand the 'MapArea' section
    • Set the PostBackValue to '#VALX' this will set the post back value to the same value as our XValueMember. (most of the chart keywords will work here reference links below)
    • Click ok and save
  2. Add a new series to the chart
    • Our existing pie-chart series holds the department name and total sales. We need a series to retain our department ID so we have a concrete value to request additional information from the database.
    • In the design view select the pie chart
    • In the properties window select the ellipsis for the 'Series' property
    • In the 'Series Collection Editor' dialog click the 'Add' button
    • For the new series set the following properties
      • ChartType = "Pie"
      • Name = "ProductCategoryReference"
      • XValueMember = "ProductCategoryName"
      • YValueMember = "ProductCategoryID"
    • Yours series should look like this:AddSeries
    • Click the 'Ok' button to close
  3. Map Product Category ID to PostBackValue
    • To reference the concrete ID in the series that we created in the previous step we must use some code.
    • Select the chart and add an event handler for the "DataBound" event.
    • Go to the code behind and add the following code
    • The code appends the ProductCatogoryID from the second series to the post back values of the original series
         1: protected void Chart1_DataBound(object sender, EventArgs e)
         2: {
         3:    Chart chart1 = (Chart)sender;
         4:    int dpCount = chart1.Series[0].Points.Count;
         5:    for (int x = 0; x < dpCount; x++)
         6:    {
         7:        DataPoint ptRef = chart1.Series["ProductCategoryReference"].Points[x];
         8:        DataPoint ptTarget = chart1.Series["Series1"].Points[x];
         9:        ptTarget.PostBackValue += string.Format(",{0}", Convert.ToString(ptRef.YValues[0])); ;
        10:    }
        11: }
  4. Add Click event handler to the Chart control

    • Add code to capture our post back values
    • Add a session variable to retain the selected product category id
         1: protected void Chart1_Click(object sender, ImageMapEventArgs e)
         2: {
         3:     string[] postValues = e.PostBackValue.Split(',');
         4:     int productCategoryID = int.Parse(postValues[1]);
         5:     Session["ProductCategoryID"] = productCategoryID;
         6: }
  5. Drag a new SQLDataSource on to the design surface
    • Configure the data source (see my configuration below)
    • Be sure to add the session parameter to the query
         1: <asp:SqlDataSource ID="sqlSalesByProductCategory" runat="server" 
         2:     ConnectionString="<%$ ConnectionStrings:SalesDatabaseConnectionString %>" 
         3:     ProviderName="<%$ ConnectionStrings:SalesDatabaseConnectionString.ProviderName %>"
         4:     SelectCommand="SELECT ProductName, COUNT(P.ProductID) CountOfSales FROM ProductCategory PC INNER JOIN Product P on PC.ProductCategoryID = P.ProductCategoryID INNER JOIN Sale S ON P.ProductID = S.ProductID WHERE PC.ProductCategoryID = @SessionProductCategoryID Group By ProductName">
         5:     <SelectParameters>
         6:         <asp:SessionParameter Name="SessionProductCategoryID" SessionField="ProductCategoryID" DbType="Int32" />
         7:     </SelectParameters>            
         8: </asp:SqlDataSource>
  6. Add our detail graph (Line Graph)
    • From the toolbox drag/drop a new Chart onto the design surface
    • Set the following properties by selecting the smart tag carrot '>' when viewing the chart control on the design surface:
      • Choose Data Source = "sqlSalesByProductCategory"
      • Chart Type= "Column"
      • X Value Member  = "ProductName"
      • Y Value Member = "CountOfSales"barchartproperties
  7. That's it!!
    • Save your work and press F5 to run
    • Clicking an area on the pie chart will cause the bar chart to be populated.

FinishedProduct

Now you may have noticed the ugly post back process that repaints the screen for each click of the pie chart (this is easily solved by using an Ajax Update Panel control) who knows maybe a future blog.

~Happy Charting~

Jim

Chart Control Keywords (MSDN)

Visual Studio 2010 C# Project Source (Chart Drill Down)

We're Hiring!!!

   Posted by: Intertech

Thanks to our loyal customers and the great work our team members are doing for those customers, we are growing. We're looking for top talent to join our award winning team. Our staff get to teach the top firms in the country on the latest technologies or use those same technologies to build great new application for clients.

If you like solving challenging problems with great technology this might be the place for you.

Here are some of the needs we have:

·         Senior Developer/Architect (.Net Silverlight WPF WCF)

·         C# ASP.NET Developer

·         Software Developer (.Net)

·         Software Developer (ASP.Net MVC)

·         Software Developer (C# ASP.NET)

·         Sr. Systems / Software Engineer ( C#.Net )

·         .Net Manufacturing Systems / Solutions Architect

·         C#.Net developer

·         .Net Developer

·         Systems / Solutions Architect (.Net Manufacturing)

·         ASP.Net MVC Developer

·         Senior .Net Silverlight WPF WCF Developer/Architect

·         Sr. C#.Net Systems / Software Engineer

·         Senior Java Developer\Architect

 

For more details on our jobs, click here.

 

You can also apply online or if you find a job that is perfect for a friend, we make it easy for you to send it to them.

 

Let us know if you find one that is perfect for you or if you know someone who may be a great fit.

 

We’re offering a free training certificate to anyone who refers someone that joins our firm.

 

Thanks!

 

 

Create ASP.NET 4.0 Pie Chart with Tooltips

   Posted by: Jim Rouse

If you?re new to ASP development or if you?re like myself and have developed applications for many years, and do not routinely revisit all of the controls for every .NET release, if you haven't already, I would strongly suggest reviewing Microsoft?s ASP.NET 4.0 charting controls before purchasing a third party charting control package.

If you?re familiar with the charting components of Excel you will find the ASP Charting controls to provide a similar set of chart templates and functionality.  The ASP.NET 4.0 Chart control provides such a rich set of functionality that I would argue that using this control should satisfy the majority of your charting needs.

In this example I will introduce ASP Charting control by showing how quickly you can build a pie chart, associate it to a Sql data source set up the series and display tool-tips.
The basic steps in the is example is:

  1. Create the data model
  2. Create web application
  3. Add a data source
  4. Add chart control
  5. Add chart tooltips

Data Model

As with all charting needs we need to have some data to that will be represented by our chart.  The following diagram shows the data model that I used for this example:

DataModel

The data model consists of a products table where a given product is grouped by a product category.  As each product has been sold there is a corresponding record of that sale in the Sale table.

Web Application

  1. Open Visual Studio
  2. Create a New ASP.NET Empty Web Application
  3. Add a new Web Form (.aspx) page to the project
  4. Open the design view for the web form added in the previous step.

Data Source

  1. With the web form design view visible expand the "Data" section in the tool box
  2. Drag & drop a new Sql Data Source object onto the body of the web form.
  3. In the design view select the Sql Data Source object that was just added and click the carrot that appears then select "Configure Data Source".
  4. Select or create a New Connection string
  5. After defining your connection string click "Next>" 
  6. On the "Configure the Select Statement" screen select the radio button for "Specify a custom SQL statement or stored procedure
  7. On the screen "Define Custom Statements or Stored Procedures" make sure the "Select" tab is selected
  8. Select the radio button for "SQL statement" 
  9. For the data model above use the following SQL statement in the text field:
       1: SELECT PC.ProductCategoryName, PC.ProductCategoryID, SUM(S.Price) TotalSales 
       2: FROM ProductCategory PC 
       3: INNER JOIN Product P on PC.ProductCategoryID = P.ProductCategoryID 
       4: INNER JOIN Sale S ON P.ProductID = S.ProductID 
       5: Group By PC.ProductCategoryID, PC.ProductCategoryName
       
  10. Click the "Next>" button
  11. You can test the query to verify expected results 
  12. Finally click the "Finish button"

TestQueryscreen

Chart Control

  1. Expand the "Data" section in the toolbox
  2. Drag/drop a "Chart" control onto the design service in the body of the web form
  3. Select the Chart control just added to the design surface and select the carrot.
  4. In the "Choose Data Source" select the Sql Data Source object that was defined in earlier steps
  5. Set the "Chart Type" drop down to "Pie"
  6. Set the "X Value Member" to ProductCategoryName
  7. Set the "Y Value Member" to TotalSales

At this point running the application provides a nice pie chart with the corresponding category labels.

Chart

Chart Tooltips
*Adding tooltips is an easy task and one that is commonly requested, and expected by end users.

  1. Select the Chart control on the design surface
  2. Open the properties window
  3. Locate the "Series" property and click the ellipsis to open the "Series Collection Editor"
  4. In the left pane make sure "Series1" is highlighted
  5. On the right pane scroll down until you locate "ToolTip"
  6. Click the ellipsis to open the "String Keywords Editor" dialog
  7. In the String Keywords Editor dialog click the button "Insert New Keyword"
  8. Select the option "Y Value as Percentage of Total"
    1. You can customize the formatting of the tooltips by changing values in the "Format" drop down.
    2. To create your own custom formatting select the "Custom" option in the "Format" drop down list.
  9. Click the "Ok" button on Keyword Editor dialog
  10. Click the "Ok" button on the String Keywords Editor dialog.
  11. Click the "Ok" button on the Series Collection Editor dialog.
  12. Run the application you should see tooltips specific to each section of the pie graph. 

ChartWithTooltip

Hopefully at this point you will feel comfortable exploring the various chart types their associated properties.  Microsoft chart control is a fairly simple control with numerous features.  In future blogs I will provide additional charting examples.

~Happy Charting~

Visual Studio 2010 C# Project Source

SQL Database and Sample Data

Find Us
Contact Us 651-288-7000 1-800-866-9884
Home | Training | Curriculum | Course Finder | Schedule | Enroll | Twin Cities Java User Group | Consulting | Foundation | Jobs | About Us | Our Story | Press Room | Instructors | President | Map & Directions | Sitemap

Java Training | JSF / Struts / Spring / Hibernate Training | Java Power Tools Training | .NET 4.0 & Visual Studio 2010 Training | Microsoft Web Development Training | Prism / MVVM / MEF Training | .NET 3.5 and Visual Studio 2008 Training | .NET 2.0 and Visual Studio 2003 Training | Cloud Computing Training | Ajax / Web Services / XML Training | Groovy and Grails Training | SQL Server 2012 Training | SQL Server 2008 Training | SQL Server 2005 Training | Mobile Development Training | SharePoint 2010 Training | SharePoint 2007 Training | Agile, Process, Analysis & Design Training | Arch/Design Patterns Training | Microsoft Official Curriculum Training | Web Development Training | Ruby Training | Rational Application Developer (RAD) Training | WebSphere Application Server Training | WebSphere Portal Training | WebLogic Training | Boot Camp Training | Project Management Training | C / C++ Training | Metro / WinRT / Windows 8 Development Training | Retired

Intertech delivers training on-site and virtually serving cities including Phoenix, AZ | San Francisco, CA | Los Angeles, CA | San Diego, CA | San Jose, CA | Washington, DC | Chicago, IL | Orlando, FL | Boston, MA | Duluth, MN | Minneapolis St. Paul, MN | Rochester, MN | Raleigh-Durham, NC | New York, NY | Philadelphia, PA | Austin, TX | Dallas, TX | Houston, TX | Seattle, WA.