0

I am following this post, to build a bar chart and show on my webpage. Below is the code i have done to accomplish it:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);            
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from ForChart";
cmd.CommandType = CommandType.Text;            

SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet, "Query");

foreach (DataRow row in myDataSet.Tables["Query"].Rows)
{
    string seriesName = row["SalesRep"].ToString();
    Chart1.Series.Add(seriesName);
    Chart1.Series[seriesName].ChartType = SeriesChartType.Line;
    Chart1.Series[seriesName].BorderWidth = 2;
    for (int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)
    {
        string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;
        string YVal = Convert.ToString(row[columnName]);
        Chart1.Series[seriesName].Points.AddXY(columnName, YVal);
    }
}

GridView1.DataSource = myDataSet;
GridView1.DataBind();
cmd.Connection.Close();

And my table is having the below data. Please check the snapshot

enter image description here

But when i run the code i am getting the below error. Please help me to resolve the issue:

A chart element with the name 'John' already exists in the 'SeriesCollection'.

I am not able to traverse the records thats why i am getting this error, but i don't know how to traverse through all the records.

Coding help would be very much appreciated. Thanks.

HarshSharma
  • 630
  • 3
  • 9
  • 34

1 Answers1

0

I'm assuming that Chart1.Series requires unique names, and thus this call will fail when you try to enter the same name multiple times:

Chart1.Series.Add(seriesName);

Ugh, that entire example on MSDN is filled with bad practices:

  • select *
  • no usings used with SqlConnection, SqlCommand,...
  • mixing UI code and DB code (they should be in separate classes)

Look at this example for a possible solution.

Community
  • 1
  • 1
BCdotWEB
  • 1,009
  • 1
  • 14
  • 35