endeka
endeka

Reputation: 121

c# Set SQL-query result into chart

I'm new with C# so this can be a stupid question but google didn't help me.

I've created a new project (SharePoint 2016 Empty Project and then added a Visual Web Part) in Visual Studio and in my ascx-file i've created an empty chart "ChartExample".

In my ascx.cs-file I have a query where I'm getting the information from a SQL-server. I can use this information for a gridview but how can I set this data into my chart?

I've tried a lot of things but always getting errors.

This is the current code I have (without code to add content to my chart)

SqlConnection conn = new SqlConnection("server=***;database=***;user id=***;password=***");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select column1 , column2 from dbo.myTable";
da.SelectCommand = cmd;
DataSet ds = new DataSet();

conn.Open();
da.Fill(ds);
//Working code for GridView
GridView.DataSource = ds;
GridView.DataBind();

conn.Close();

So how can I add the same result into a chart?

This is the code in my ascx file:

<asp:Chart ID="ChartExample" runat="server">
   <Series>
       <asp:Series Name="Example"></asp:Series>
   </Series>
   <ChartAreas>
       <asp:ChartArea Name="ChartExample"></asp:ChartArea>
   </ChartAreas>
</asp:Chart>

Upvotes: 0

Views: 5004

Answers (1)

endeka
endeka

Reputation: 121

Found the solution:

SqlConnection conn = new SqlConnection("server=***;database=***;user id=***;password=***");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select column1 , column2 from dbo.myTable";
da.SelectCommand = cmd;
DataSet ds = new DataSet();

conn.Open();
da.Fill(ds);
this.ChartExample.DataSource = ds.Tables[0];

//Mapping a field with x-value of chart
this.ChartExample.Series[0].XValueMember = "column1";

//Mapping a field with y-value of Chart
this.ChartExample.Series[0].YValueMembers = "column2";

//Bind the DataTable with Chart
this.ChartExample.DataBind();

conn.Close();

Upvotes: 1

Related Questions