GridLines
go with DataPoints
and Labels
go with GridLines
, but..
You can set the Interval
and the Minimum
for the X-Axis
to tweak them apart :
but there are a few extras to watch out for..
// get a reference
ChartArea chartArea1 = chart1.ChartAreas[0];
// don't start at 0
chartArea1.AxisX.IsStartedFromZero = false;
// pick your interval
double interval = 1D;
chartArea1.AxisX.MajorTickMark.Interval = interval;
// set minimum at the middle
chartArea1.AxisX.Minimum = interval / 2d;
// pick a column width (optional)
chart1.Series[0].SetCustomProperty("PixelPointWidth", "30");
// we want the labels to sit with the points, not the grid lines..
// so we add custom labels for each point ranging between the grid lines..
for (int i = 0; i < chart1.Series[0].Points.Count; i++)
{
DataPoint dp = chart1.Series[0].Points[i];
chartArea1.AxisX.CustomLabels.Add( (0.5d + i) * interval,
(1.5d + i) * interval, dp.XValue.ToString());
}
Update:
As your updated question shows, you are using data-binding with strings as X-Values. This is very convenient, but goes against the core nature of the Chart control. All its xalues, be it X-Value
or any of the Y-Values
are internally stored as doubles.
Random strings don't convert to double and while you can conveniently add DataPoints
with strings as X-Values
, all sorts of ugly issues come up as a consequence.
First have a look at the X-Values
themselves: As I said they are double; when you check their values you will see they all are 0. And where are the string values? They are placed in the labels.
One problem often found it that you now can't access the X-Values
with value expressions.
Another problem is that we now can't give a range of x-Values
for custom labels.
Solution: If we need custom labels, we must change the data!
Data binding is fine, just make sure to add a numeric column to you datasource containing a month number and set it as the XValueMember
of the series!
You can make that column it invisible in your DataGridView
.
Finally you will want to create the custom labels, pretty much as before; just change their content to pull from the string column containing the month names.
Here is what it looks like here:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…