我想使用SQlDatareader对象在我的图表上绘制Y轴。该列中包含int值。我正在通过代码生成图表。任何帮助将不胜感激,因为我真的很接近我的目标,但只是在这里。以下是我的代码。我实际上无法将Type dr转换为数组。
SqlCommand cmd = new SqlCommand("select items from student_info", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
int[] yValues = { //Here I want the dr };
string[] xValues = { "Coke", "Pepsi","Coffee"};
Chart chart = new Chart();
Series series = new Series("Default");
series.ChartType = SeriesChartType.Column;
chart.Series.Add(series);
ChartArea chartArea = new ChartArea();
Axis yAxis = new Axis(chartArea, AxisName.Y);
Axis xAxis = new Axis(chartArea, AxisName.X);
chart.Series["Default"].Points.DataBindXY(xValues, yValues);
chart.ChartAreas.Add(chartArea);
chart.Width = new Unit(500, System.Web.UI.WebControls.UnitType.Pixel);
chart.Height = new Unit(200, System.Web.UI.WebControls.UnitType.Pixel);
string filename = "C:\\check\\Chart.png";
chart.SaveImage(filename, ChartImageFormat.Png);
Panel1.Controls.Add(chart);
}
答案 0 :(得分:1)
类型dr = DataRow
返回,正如名称所示,ROW
。所以它返回一个值。
如果要向数组中添加许多值,并且想要使用数据库中的值,则需要创建一个数组并使用DataRows的结果填充它,同时循环查看从查询中获取的值
但是我建议你为此使用List<>而不是数组,然后使用方法ToArray。
Examplecode:
List<int> xValues = new List<int>();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows) //Check if datareader is not null, allways do this.
while (dr.Read())
{
int number;
bool result = Int32.TryParse(dr["items"], out number);
if (result) //check if its really a number
{
xValues.Add(number);
}
else
{
number = 0; //no number, so just assign 0 to the list
xValues.Add(number);
}
}
然后如果添加xValues和yValues:
chart.Series["Default"].Points.DataBindXY(xValues.ToArray(), yValues);
答案 1 :(得分:0)
首先从sqldatareader创建数组。然后用它来生成图表。 您还将图表代码放在while循环中。这将创建一个图表并将其添加到student_info表中每行的面板中。所以将图表代码放在while循环之外。
List<int> list = new List<int>();
SqlCommand cmd = new SqlCommand("select items from student_info", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
list.Add(Convert.ToInt32(dr[0])); //getting all values in a List
}
int[] yValues = list.ToArray<int>(); //create your array here then use it
string[] xValues = { "Coke", "Pepsi","Coffee"};
Chart chart = new Chart();
Series series = new Series("Default");
series.ChartType = SeriesChartType.Column;
chart.Series.Add(series);
ChartArea chartArea = new ChartArea();
Axis yAxis = new Axis(chartArea, AxisName.Y);
Axis xAxis = new Axis(chartArea, AxisName.X);
chart.Series["Default"].Points.DataBindXY(xValues, yValues);
chart.ChartAreas.Add(chartArea);
chart.Width = new Unit(500, System.Web.UI.WebControls.UnitType.Pixel);
chart.Height = new Unit(200, System.Web.UI.WebControls.UnitType.Pixel);
string filename = "C:\\check\\Chart.png";
chart.SaveImage(filename, ChartImageFormat.Png);
Panel1.Controls.Add(chart);