Thursday, 21 June 2012

Draw a graph in c# .net

I’m going to give you a tutorial about how to draw graphs using a component called Chart



I first created a new application, added the Chart component in "Default.aspx"



It looked like this. Lets start coding

In Default.aspx


<asp:Chart ID="Chart2" runat="server" ViewStateContent="All" 
Width="670px" Palette="Bright" BackColor="LightGray"
BackGradientStyle="LeftRight" BorderlineColor="Transparent"
PaletteCustomColors="128, 128, 255">
<Series>             <asp:Series Name="Series1" BackGradientStyle="TopBottom"
BorderColor="Red" ChartType="Spline" IsValueShownAsLabel="True"

LabelBackColor="White" Legend="Legend1" MarkerStyle="Circle"
YValuesPerPoint="2"> </asp:Series>         </Series>         <ChartAreas>             <asp:ChartArea BackColor="#00CCCC" BorderDashStyle="Solid" IsSameFontSizeForAllAxes="True" Name="ChartArea1">                 <AxisY ArrowStyle="Triangle" InterlacedColor="Black" Title="Number of visitor" TitleForeColor="DarkCyan"></AxisY>                 <AxisX ArrowStyle="Triangle" InterlacedColor="Black"
Interval="1" Title="Month" TitleForeColor="DarkCyan"></AxisX>             </asp:ChartArea>         </ChartAreas>         <Legends>             <asp:Legend BackColor="#D2D2D2" LegendStyle="Row" Name="Legend1" TableStyle="Wide" Title="System"></asp:Legend>         </Legends>         <Titles>         </Titles>     </asp:Chart>

In Default.aspx.cs


string path = ConfigurationManager.ConnectionStrings["ConnectionPath"]
              .ConnectionString;

        SqlConnection con = new SqlConnection(path);

        SqlCommand cmd = new SqlCommand();

        cmd.Connection = con;

        con.Open();

        cmd.CommandText = "SELECT TOP 5 premium, StateID, State 

         FROM PremiumCollection GROUP BY StateID, State";

        cmd.CommandType = CommandType.Text;

        SqlDataAdapter adp = new SqlDataAdapter(cmd);

        DataSet dt = new DataSet();

        adp.Fill(dt);

        con.Close();

        Chart2.DataSource = dt;

        Chart2.Legends.Add("leads");

        Chart2.Series["Series1"].XValueMember = "StateID";

        Chart2.Series["Series1"].YValueMembers = "premium";

        Chart2.Series["Series1"].MarkerBorderColor = 
                                           System.Drawing.Color.Red;

        Chart2.DataBind();

and add the following lines in Web.config file


 <handlers>

      <remove name="ChartImageHandler" />

      <add name="ChartImageHandler" preCondition="integratedMode" 
      verb="GET,HEAD,POST"

        path="ChartImg.axd" type="System.Web.UI.DataVisualization.
    Charting.ChartHttpHandler, System.Web.DataVisualization, 
    Version=4.0.0.0, Culture=neutral, 
    PublicKeyToken=31bf3856ad364e35" />

    </handlers>

The result is looked like shown the above graph image.Anything you would like to add, please use the comment area below.

1 comment: