【发布时间】:2015-03-27 14:09:16
【问题描述】:
我有一个系列,用数据库中的记录填充我的图表。显示了 7 条记录,但颜色相同。
我正在尝试更改每个条形颜色但没有成功
以下是我尝试过的行,但我给了我一个大绿条(:
private void button1_Click(object sender, EventArgs e)
{
/*First empty the chart2 to fire the current data*/
if (cbChart.SelectedItem == null)
{
chart.Visible = false;
chart.Controls.Clear();
}
else
//pnchart.Controls.Clear();
chart.Visible = true;
chart.Titles.Clear();
/*Add a new title*/
Title bezeichung = new Title("Finance" + Environment.NewLine + "(GWU)", Docking.Top, new Font("Yu Gothic", 8, FontStyle.Bold), Color.Black);
chart.Titles.Add(bezeichung);
chart.Titles.Add(bezeichung2);
if (cbChart.SelectedItem != null)
{
string S = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(S);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = ("[dbo].[storedprocedure]");
cmd.Parameters.AddWithValue("@Table_Name", cbChart.SelectedValue.ToString());
SqlDataReader myReader; // DataReader to just read Data from the Datbase
try
{
//DO SOMETHING
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
//Parameters (Seriesname, x-axis data & y-axis data)
this.chart.Series["Series"].Points.AddXY(myReader["Finance"], myReader["GWU"]);
// remove grid lines
chart.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
chart.ChartAreas[0].AxisY.MajorGrid.LineWidth = 0;
chart.ChartAreas[0].AxisX.LabelStyle.Angle = -45;
chart.Series["series1"].Points[0].Color = Color.Green;
chart.Series["series1"].Points[1].Color = Color.Red;
chart.Series["series1"].Points[2].Color = Color.PowderBlue;
chart.Series["series1"].Points[3].Color = Color.Peru;
chart.Series["series1"].Points[4].Color = Color.Pink;
chart.Series["series1"].Points[5].Color = Color.Purple;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
else
{
MessageBox.Show("Bitte ", "Info", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
这是我运行后收到的错误信息: 索引在有效范围之外,索引不能为负并且必须小于列表的大小
以及点击按钮后的图表:
【问题讨论】:
-
您的图表对象是什么类型?
-
一个按钮对象。如果单击 btn,它将连接到数据库并填充图表。
-
您的代码应该可以正常工作。您每次添加数据点后都运行它吗?是
ChartType = Column? -
一个Button没有Series属性,所以它显然不是一个Button。如果您导航到
chart的定义,它是什么类的实例,这就是我要问的...... -
@Zack:你觉得它是什么?很明显它是一个
Chart控件。