28 February 2012

This BackgroundWorker states that it doesn't report progress/cancellation. Modify WorkerReportsProgress to state that it does report progress.

Error Type1:  This BackgroundWorker states that it doesn't report progress. Modify WorkerReportsProgress to state that it does report progress.
The error occurs when the WorkerReportsProgress of the background worker is not set to true.

This should be set (to True ) from the properties window as shown below screen.

Error Type 2: This BackgroundWorker states that it doesn't support cancellation. Modify WorkerSupportsCancellation to state that it does support cancellation
The error occurs when the WorkerSupportsCancellation of the background worker is not set to true.
This should be set (to True ) from the properties window as shown below screen.


Using Background Worker in C#

Most of our application that we develop today require simultaneous functions to perform but with performance.  Working with Microsoft .NET framework we have worked with threads through which we can handle all the tasks simultaneously under one main application thread. You can perform smaller operations with the help of Threading class, instead I prefer using Background Worker class to implement to perform all my heavy duty operations.
Background worker class is introduced in .NET framework 2.0 and using this class makes it easy to execute long running operations on a separate thread, support cancellation, progress reporting and marshalling results back to the UI thread.
Now we will see how to use background worker class to perform heavy operations.
My requirement is execute more than one form code simultaneously. Each form, connect to the database and start the execution back end it takes more than one day. Each form will behave same.  To do this i have choose Back Ground Worker.  
I have four buttons to open four forums when i click each one them, a new window will open and then i will start the execution of functionality.
Now let start working with BackgroundWorker.
Create four forms as shown bellow.

First, you need an instance of BackgroundWorker class,Get to the design mode and drag & drop the background worker component on form,  form Component tab of Toolbox as shown bellow screen.
Set the properties of the background worker:
Set GenerateMember and Modifiers as it is. In the sample application we have a progress bar which reports the percentage of the task completed so we need to set the WorkerReportsProgress to true and similarly if we want the user to cancel the running operation then set the WorkerSupportsCancellation to true.

Now the next step is to create 3 event methods:
1.) DoWork: This is the main method which is responsible to handle the large operation. The code here is not different than the usual code.
2.) ProgressChanged: This method reports the change in the progress of the operation performed by the background worker DoWork method.
3.) RunWorkerCompleted:Thismethod checks the RunWorker Completed Event Args and perform action accordingly.
Starting with the Start button:
Next step is to set the event handlers of you object, and finally you have to call RunWorkerAsync() method.  Whenever you call this method it get a free thread from CLR and fires DoWork event. Now you put your codes (The codes that you want to be executed in another thread) in event handler of DoWork event. If the code completed it will raise an event called RunWorkerCompleted to notify you. It 's important to know that this event is not raised on the new thread instead, it will be raised on main thread of your application.

private void btn_start_Click(object sender, EventArgs e)
{
//Starts the backgroundworker process asynchronously
backgroundWorker1.RunWorkerAsync();
btn_start.Enabled = false;
} 
The DoWork method: 
The event args of DoWork event is an object of type DoWorkEventArgs.
In this object you have a property called Argument for getting what you have passed in RunWorkerAsync() method. You can use it in your time-consuming task. 
//Background worker DoWork method. Here we will perform our heavy duty tasks.
//I have used a simple datareader object to traverse all the rows in the table.
//The table has around 19K rows.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  try
  {
    int i = 0;
    cmd = new SqlCommand("SELECT * FROM Person.Contact", con);
    con.Open();
    dr = cmd.ExecuteReader();
    while(dr.Read())
    {
        i = i + 1;
        //report to the backgroungworker progreechanged event of the background worker class
        backgroundWorker1.ReportProgress(i);
        Thread.Sleep(1);
        //Called and check if the cancellation of the operation is pending. If returned true
        //DoWorkEventArgs object cancels the operation.
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            return;
        }
    }
   }
   catch (Exception x)
   {
    MessageBox.Show("An error occured while performing operation" + x);
   }
   finally
   {
    con.Close();
   }
}
The RunWorkerCompleted Method:
You may want to have the result of your task in your UI. Again for this purpose you have a property called Result which you can set it in your DoWorkEventArgs. And it will be accessible in your RunWorkerCompletedEventArgs of RunWorkerCompleted event.
private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        MessageBox.Show("Operation Cancelled");
        btn_start.Enabled = true;
    }
    else
    {
        MessageBox.Show("Operation Completed");
        btn_start.Enabled = true;
    }
}
The ProgressChanged Method:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //Report porogress bar change
    progress.Value = e.ProgressPercentage;
}
Ending up with the cancel button:
//To cancel async operation
private void btn_cancel_Click(object sender, EventArgs e)
{
     //To cancel the asynchronous operation
     backgroundWorker1.CancelAsync();
     progress.Value = 0;
     btn_start.Enabled = true;
}
So when your application is traversing the records and suddenly you think that you should quit the job and work on other part of the application, just hit the cancel button and the large operation will get cancelled without any freezing and hanging of your application.

Reference Links
4) 

24 February 2012

C#: Check if Form is already running

While implementing WinForms programming you might come across a situation where you do not want to open a form multiple times on an event.  A common practice in the event handler function is:
From1 firstForm = new From1();
firstForm.Show(); 
This will open your form, fine! But what if the event happens again and the previously opened firstForm has not been closed yet? A new firstForm will be opened and this will go on.  To check if a form is already running you’ll have to look for it in the Application.OpenForms collection. When a form is opened it is added to that collection. Here’s a boolean method that checks whether a form is open or not. This code snippet shows you how to check if is your MDI container has a specific MDI child open or not. The sample below looks though each of the mdi children in the container for a instance of the form you want to open. If an instance is found, the form is brought to the front. If an instance of the form is not found, the code opens a new instance of the form.

Boolean Method
To check whether the form is already opened or not      
      private bool CheckForm(Form form)
        {
            form = Application.OpenForms[form.Text];
            if (form != null)
                return true;
            else
                return false;
        }
Example use:
                       Form2 formSecond = new Form2();
                        if (!CheckForm(formSecond ))
                        {
                            formSecond .Show();
                        }
                        else
                        {
                            formSecond .WindowState = FormWindowState.Normal;
                            formSecond .BringToFront();
                            formSecond .Activate();
                        }

10 February 2012

Crystal Reports Set Row Height

To increase the row height in Crystal Report designer keep a TextObject in details section and drag your desired field from FieldExplorer onto it. Then, Right-Click TextObject in Details Section then select Format Object form the context menu.

When click on Format Object then it will show Format Editor Window as shown bellow. Enter the values in Minimum number of lines you wand check the Can Grow option. and then click on Ok button.

Crystal Reports - How to Force Page Break On Rows Count

I have a report that I am designing that requires that a new page be generated if rows has more than 8 then second page needs to be generated. To do that follow the steps.
Step 1:  Create a formula to get the rows count for that select field explorer and then expand the formula fields. 

Step 2:  Right click on Forumla Fields and select New to create a formula.  It will show a popup window then enter formula name and "Use Editor" as show bellow.
Step 3:  When click on Use Editor button it will show Formula Editor window.  Here you will write the condition to get rows count as shown bellow. Drag and drop the field.


The Formula Would be:
ToNumber({REP.TotalEmps})

Step 4:  You have created  a formula and use it in the report for page break if rows count increases as per your requirement. Right-click on the Group Header in the Design tab, select "Section Expert" as shown below and then it will show Section Expert window.

 Step 5:  From the section Expert window Select the "New Page After" checkbox and click on the formula edit button then it will show a window to write formula as show bellow and click on save and close.

The formula says that when the employee count greater than 8 then remaining records will be print in the next page. Based on your requirement change the count value.

Crystal Reprts Page breaks (on filed Values changes from one page to another)

You have a date column in crystal report.  When date values changes those details should display in the next page. To get this effect you keep the check mark in the “New Page After” of Group, but you change the “New Page After” for Group Footer Section  to be a condition formula.  To do that Follow the steps
Step 1: Right click on "GroupFooterSection" and select "Section Expert" as shown below.

Step 2: When click on Section Expert then it will show sections window check the "New Page After" and click on Formula Editor button then it will show a window to write formula.

Step 3: Then drag and drop the field which and write the condition and then click on Save and Close button.


The formula would be:
{Table.date} = Next ( {Table.date} )

The formula says that when date changes it allowed to do the page break as long as the report date differ form one page to another.

06 February 2012

Chart Elements Overview

A chart consists of numerous elements, all of which are accessible via the Chart control API. The Chart control API is object-oriented, extensible and highly flexible. It also supports an unlimited number of key chart elements such as data series, data points in a series, chart areas, and so on.
The following figure illustrates the key elements that constitute a chart:
Description of Chart Elements
The following lists describes the major chart components:  

Axis Label
A label along an axis.  

Axis Title
The title of an axis.

Chart Area
The chart picture consists of one or more chart areas, which are rectangular areas that are used to draw series, labels, axes, grid lines, tick marks, and so on. Multiple series can be plotted in one chart area, depending on the chart types involved.
The plot area, used to plot chart data, is also contained within a chart area.

Chart Picture
The chart picture, is the entire image surface that is rendered by the Chart control. It corresponds to the root Chart object.  

Chart Series
A series is a related group of data points. Each series is associated with a chart type.

Legend
A legend for the Chart picture. There can be an unlimited number of legends in a chart.

Grid Lines
There are major and minor horizontal and vertical grid lines, which usually occur in conjunction with tick marks.

Tick Marks
There are major and minor horizontal and vertical tick marks, which usually occur in conjunction with grid lines.

Plot Area
The plot area is the inner rectangular area within a chart area that is used to plot series and grid lines. Labels, tick marks, the axis title, and so on, are all drawn outside of the plotting area and inside the chart area. The plot area can be set via the ChartArea.InnerPlotPosition property.

Title
A main chart title. There can be an unlimited number of titles placed in a chart image. Note that custom text can be displayed using GDI+ and the paint-related events.

Value Label
A special label that occurs for a data point, slightly offset from where the point is plotted. It can be the data point's value or custom text.

MS Chart Control: Getting Started

The Main Components of a Chart
The Chart control renders a single "Chart Picture." The Chart Picture may be composed of multiple charts - say, a line chart and a bar chart. Each chart within the Chart Picture is referred to as a Chart Area. (Typically the Chart control will have only one Chart Area.) A chart contains one or more series, which are associated with a particular Chart Area. A series is a collection of data points. How the series is rendered depends on its type. A series configured to display as a line will render its data points as a continuous line. To have multiple lines in the chart you would define one series for each line. If the series is configured to display a bar or column then a bar or column is drawn for each data point.
The data points that make up a series usually have two components - an X value and a Y value - although some series types only require a single data point. For line and column series the X value indicates the position of the data point along the chart area's X axis and the Y value indicates the position of the line or the height of the column along the chart area's Y axis.

This sample chart application demonstrates how to create a basic chart in 2D and 3D that uses a code-behind page with dynamic and datasets.  Here you can find total 7 types of charts.

Using Dynamic Data Creating Charts:
Step 1: .ASPX Page
The chart area(s), series, and data points can be specified declaratively (either by entering the declarative markup by hand or via the Properties window) or programmatically in the code-behind class. Typically the series and chart area(s) are specified declaratively and the data points are populated programmatically by querying a database or some other dynamic data store. Let's start by discussing how to display a chart whose chart area, series, and data points are all specified declaratively.
  1. Column
  2. Bar
  3. Pyramid 
  4. Area
  5. Pie
  6. Line
  7. Funnel charts

<div>
        <table cellpadding="4">
            <tr>
                <td align="center">
                    Chart Type:<asp:DropDownList ID="ChartType" runat="server" Width="120px" AutoPostBack="True"
                        >
                        <asp:ListItem Value="Column">Column</asp:ListItem>
                        <asp:ListItem Value="Bar">Bar</asp:ListItem>
                        <asp:ListItem Value="Pyramid">Pyramid</asp:ListItem>
                        <asp:ListItem Value="Area">Area</asp:ListItem>
                        <asp:ListItem Value="Pie">Pie</asp:ListItem>
                        <asp:ListItem Value="Line">Line</asp:ListItem>
                        <asp:ListItem Value="Funnel">Funnel</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Chart ID="Chart1" runat="server" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)"
                        Palette="BrightPastel" ImageType="Png" BorderDashStyle="Solid" BackSecondaryColor="White"
                        BackGradientStyle="TopBottom" BorderWidth="2" BackColor="#D3DFF0" BorderColor="26, 59, 105"
                        Height="481px" Width="761px">
                        <BorderSkin SkinStyle="Emboss" />
                        <Legends>
                            <asp:Legend Name="Legend1" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"
                                IsTextAutoFit="False">
                            </asp:Legend>
                        </Legends>
                        <Titles>
                            <asp:Title Alignment="TopCenter" BackColor="180, 165, 191, 228" BackGradientStyle="TopBottom"
                                BackHatchStyle="None" Font="Microsoft Sans Serif, 12pt, style=Bold" Name="Role Summary Report"
                                Text="Role Summary Report" ToolTip="Role Summary Report" ForeColor="26, 59, 105">
                            </asp:Title>
                            <asp:Title Alignment="TopCenter" BackColor="Transparent" Font="Microsoft Sans Serif, 10pt, style=Bold "
                                ToolTip="Chart Type">
                            </asp:Title>
                        </Titles>
                        <Series>
                            <asp:Series Name="RolesCount" ChartArea="ChartArea1" Legend="Legend1" CustomProperties="DrawingStyle=Cylinder"
                                BorderColor="64, 0, 0, 0" Color="224, 64, 10" MarkerSize="5">
                                <EmptyPointStyle AxisLabel="0" />
                                <Points>
                                    <asp:DataPoint YValues="6" />
                                    <asp:DataPoint YValues="9" />
                                    <asp:DataPoint YValues="5" />
                                    <asp:DataPoint YValues="7.5" />
                                    <asp:DataPoint YValues="5.69999980926514" />
                                    <asp:DataPoint YValues="3.20000004768372" />
                                    <asp:DataPoint YValues="8.5" />
                                    <asp:DataPoint YValues="7.5" />
                                    <asp:DataPoint YValues="6.5" />
                                </Points>
                            </asp:Series>
                        </Series>
                        <ChartAreas>
                            <asp:ChartArea Name="ChartArea1" BackColor="64, 165, 191, 228" BackSecondaryColor="White"
                                BorderColor="64, 64, 64, 64" ShadowColor="Transparent" BackGradientStyle="TopBottom">
                                <AxisY LineColor="64, 64, 64, 64" IsLabelAutoFit="false" Title="Roles Count" ArrowStyle="Triangle">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisY>
                                <AxisX IsLabelAutoFit="False" LineColor="64, 64, 64, 64" Title="Role Name" ArrowStyle="Triangle"
                                    Interval="1">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" IsEndLabelVisible="False" Angle="-90" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisX>
                            </asp:ChartArea>
                        </ChartAreas>
                    </asp:Chart>
                </td>
            </tr>
        </table>
    </div>

Step 2: .ASPX.CS
Based on the selected chart type the following code will be executed.  
protected void Page_Load(object sender, EventArgs e)
        {
            if (ChartType.SelectedItem.ToString() == "Bar")
            {
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Bar;
                Chart1.Titles[1].Text = "Bar Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Pie")
            {
                Chart1.Series["RolesCount"]["3DLabelLineSize"] = "100";
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
                Chart1.Series[0]["PieDrawingStyle"] = "SoftEdge";
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Pie;
                Chart1.Series["RolesCount"]["PieLabelStyle"] = "Inside";

                //Chart1.Legends["Legend1"].Enabled = true;

                Chart1.Titles[1].Text = "Pie Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Line")
            {
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Line;
                Chart1.Titles[1].Text = "Line Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Funnel")
            {
                //Chart1.Series["RolesCount"]["3DLabelLineSize"] = "100";
                Chart1.Series["RolesCount"]["FunnelStyle"] = "YIsHeight";
                Chart1.Series["RolesCount"]["FunnelLabelStyle"] = "OutsideInColumn";
                Chart1.Series["RolesCount"]["FunnelOutsideLabelPlacement"] = "Right";
                Chart1.Series["RolesCount"]["FunnelPointGap"] = "1";
                Chart1.Series["RolesCount"]["Funnel3DDrawingStyle"] = "SoftEdge";
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Funnel;
                Chart1.Series["RolesCount"]["FunnelLabelStyle"] = "Inside";
                // Set 3D angle
                Chart1.Series["RolesCount"]["Funnel3DRotationAngle"] = "5";
                // Set 3D drawing style
                Chart1.Series["RolesCount"]["Funnel3DDrawingStyle"] = "CircularBase";
                // Set minimum point height
                Chart1.Series["RolesCount"]["FunnelMinPointHeight"] = "0";
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
                Chart1.Titles[1].Text = "Funnel Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Area")
            {

                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Area;
                Chart1.Titles[1].Text = "Area Chart";
            }
            else if (ChartType.SelectedItem.ToString() == "Pyramid")
            {
                // Set pyramid data point labels style
                Chart1.Series["RolesCount"]["PyramidLabelStyle"] = "OutsideInColumn";
                // Set gap between points
                Chart1.Series["RolesCount"]["PyramidPointGap"] = "1";
                // Set minimum point height
                Chart1.Series["RolesCount"]["PyramidMinPointHeight"] = "0";
                // Set 3D mode
                Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
                // Set 3D angle
                Chart1.Series["RolesCount"]["Pyramid3DRotationAngle"] = "5";
                // Set 3D drawing style
                Chart1.Series["RolesCount"]["Pyramid3DDrawingStyle"] = "SquareBase";
                // Set pyramid value type
                Chart1.Series["RolesCount"]["PyramidValueType"] = "Linear";
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Pyramid;
                Chart1.Titles[1].Text = "Pie Chart";
            }
            else
            {
                Chart1.Series["RolesCount"].ChartType = SeriesChartType.Column;
                Chart1.Titles[1].Text = "Column Chart";
            }
        }
Using DataSource Controls Creating Charts:

Programmatically Specifying the Chart Data
The previous demo showed how to declaratively specify the chart's data points. These data points are more commonly specified programmatically. The demo displays the same chart as shown above but adds the data points programmatically in the Page_Load event handler. The Chart control's declarative markup in .aspx does not include the hard-coded <Points> collection, but is otherwise the same in that the markup defines a single chart area named MainChartArea and a single column series named Championships:


<div>
        <table cellpadding="4">
            <tr>
                <td valign="top" align="center">
                    Chart Type:
                    <asp:DropDownList ID="ChartType" runat="server" Width="120px" AutoPostBack="True">
                        <asp:ListItem Value="Column">Column</asp:ListItem>
                        <asp:ListItem Value="Bar">Bar</asp:ListItem>
                        <asp:ListItem Value="Pyramid">Pyramid</asp:ListItem>
                        <asp:ListItem Value="Area">Area</asp:ListItem>
                        <asp:ListItem Value="Pie">Pie</asp:ListItem>
                        <asp:ListItem Value="Line">Line</asp:ListItem>
                        <asp:ListItem Value="Funnel">Funnel</asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Chart ID="Chart1" runat="server" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)"
                        Palette="BrightPastel" ImageType="Png" BorderDashStyle="Solid" BackSecondaryColor="White"
                        BackGradientStyle="TopBottom" BorderWidth="2" BackColor="#D3DFF0" BorderColor="26, 59, 105"
                        Height="481px" Width="761px">
                        <BorderSkin SkinStyle="Emboss" />
                        <Legends>
                            <asp:Legend Name="Legend1" BackColor="Transparent" Font="Trebuchet MS, 8.25pt, style=Bold"
                                IsTextAutoFit="False">
                            </asp:Legend>
                        </Legends>
                        <Titles>
                            <asp:Title Alignment="TopCenter" BackColor="180, 165, 191, 228" BackGradientStyle="TopBottom"
                                BackHatchStyle="None" Font="Microsoft Sans Serif, 12pt, style=Bold" Name="Employee Data Dump"
                                Text="Employee Data Dump" ToolTip="Employee Data Dump" ForeColor="26, 59, 105">
                            </asp:Title>
                            <asp:Title Alignment="TopCenter" BackColor="Transparent" Font="Microsoft Sans Serif, 10pt, style=Bold "
                                ToolTip="Chart Type">
                            </asp:Title>
                        </Titles>
                        <Series>
                            <asp:Series Name="EmpCount" ChartArea="ChartArea1" Legend="Legend1" CustomProperties="DrawingStyle=Cylinder"
                                BorderColor="64, 0, 0, 0" Color="224, 64, 10" MarkerSize="5">
                                <EmptyPointStyle AxisLabel="0" />
                            </asp:Series>
                        </Series>
                        <ChartAreas>
                            <asp:ChartArea Name="ChartArea1" BackColor="64, 165, 191, 228" BackSecondaryColor="White"
                                BorderColor="64, 64, 64, 64" ShadowColor="Transparent" BackGradientStyle="TopBottom">
                                <AxisY LineColor="64, 64, 64, 64" IsLabelAutoFit="False" Title="Employee Count" ArrowStyle="Triangle">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisY>
                                <AxisX IsLabelAutoFit="False" LineColor="64, 64, 64, 64" Title="Facility" ArrowStyle="Triangle"
                                    Interval="1">
                                    <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" IsEndLabelVisible="False" Angle="0" />
                                    <MajorGrid LineColor="64, 64, 64, 64" />
                                </AxisX>
                            </asp:ChartArea>
                        </ChartAreas>
                    </asp:Chart>
                </td>
            </tr>
        </table>
    </div>

Code Behind :
Alternatively, you can bind data by using the Chart control's DataSource property. This involves retrieving the data from the database (or from wherever you get the data to display), assigning it to the DataSource property, and calling the Chart's DataBind method. Unlike with the DataBindTable method, when using the DataSource property you need to define a series and specify the name of the properties in the data that are to be displayed in the X and Y values in the series.  

SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
    SqlConnection con = new SqlConnection(new ConnectionString().getConnectionString());
    SqlDataAdapter da = new SqlDataAdapter();
    DataSet ds = new DataSet();
da = new SqlDataAdapter("exec StoredProcedure", con);
        da.Fill(ds, "EmpDataDump");
        if (ds.Tables["EmpDataDump"].Rows.Count > 0)
        {
Chart1.DataSource = ds.Tables["EmpDataDump"];

        // Set series members names for the X and Y values
        Chart1.Series["EmpCount"].XValueMember = "City";
        Chart1.Series["EmpCount"].YValueMembers = "EmpCount";
        Chart1.Series["EmpCount"].IsValueShownAsLabel = true;


        if (ChartType.SelectedItem.ToString() == "Bar")
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Bar;
            Chart1.Titles[1].Text = "Bar Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Pie")
        {
            Chart1.Series["EmpCount"]["3DLabelLineSize"] = "100";
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = false;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
            Chart1.Series[0]["PieDrawingStyle"] = "SoftEdge";
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Pie;
            Chart1.Series["EmpCount"]["PieLabelStyle"] = "OutsideInColumn";
            Chart1.Series["EmpCount"]["PieOutsideLabelPlacement"] = "Right";
            Chart1.Titles[1].Text = "Pie Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Line")
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Line;
            Chart1.Titles[1].Text = "Line Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Funnel")
        {
            Chart1.Series["EmpCount"]["FunnelStyle"] = "YIsHeight";
            Chart1.Series["EmpCount"]["FunnelLabelStyle"] = "OutsideInColumn";
            Chart1.Series["EmpCount"]["FunnelOutsideLabelPlacement"] = "Right";
            Chart1.Series["EmpCount"]["FunnelPointGap"] = "1";
            Chart1.Series["EmpCount"]["Funnel3DDrawingStyle"] = "SoftEdge";
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Funnel;
            Chart1.Series["EmpCount"]["Funnel3DRotationAngle"] = "5";
            Chart1.Series["EmpCount"]["Funnel3DDrawingStyle"] = "CircularBase";
            Chart1.Series["EmpCount"]["FunnelMinPointHeight"] = "0";
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Inclination = 15;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Rotation = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Perspective = 10;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsRightAngleAxes = false;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.WallWidth = 0;
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.IsClustered = false;
            Chart1.Titles[1].Text = "Funnel Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Area")
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Area;
            Chart1.Titles[1].Text = "Area Chart";
        }
        else if (ChartType.SelectedItem.ToString() == "Pyramid")
        {
            Chart1.Series["EmpCount"]["PyramidLabelStyle"] = "OutsideInColumn";
            Chart1.Series["EmpCount"]["PyramidPointGap"] = "1";
            Chart1.Series["EmpCount"]["PyramidMinPointHeight"] = "0";
            Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
            Chart1.Series["EmpCount"]["Pyramid3DRotationAngle"] = "5";
            Chart1.Series["EmpCount"]["Pyramid3DDrawingStyle"] = "SquareBase";
            Chart1.Series["EmpCount"]["PyramidValueType"] = "Linear";
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Pyramid;
            Chart1.Titles[1].Text = "Pyramid Chart";
        }
        else
        {
            Chart1.Series["EmpCount"].ChartType = SeriesChartType.Column;
            Chart1.Titles[1].Text = "Column Chart";
        }
        // Data bind to the selected data source
        Chart1.DataBind();
         }

The resulting chart, when viewed through a browser, is shown below.
Column Chart:

Bar Chart:
Pyramid: (3D Chart)




Area:(3D Chart)

Pie:(3D Chart)

Line:

Funnel:(3D Chart)