我正在构建一个C#winform应用程序以在图表上显示点。我使用组合框选择每个Serie的ChartType。当尝试将不兼容的ChartType放在一起时(例如,点和甜甜圈),应用程序崩溃了。
我正在尝试使用try-catch语法捕获此异常,但是我无法使其正常工作。
private void Cb_curve_type_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
_chart.Series[_serie_name].ChartType = (SeriesChartType)cb_curve_type.SelectedIndex;
_chart.Update();
} catch (InvalidOperationException ex)
{
MessageBox.Show("Impossible to mix chart type", "Error", MessageBoxButtons.OK);
cb_curve_type.SelectedIndex = (int)_chart.Series[_serie_name].ChartType;
return;
}
}
我试图删除(InvalidOperationException ex)
来捕获所有异常,但仍然无法正常工作,并且程序在_chart.Update()
上引发了System.InvalidOperationException
这是堆栈跟踪:
à System.Windows.Forms.DataVisualization.Charting.ChartTypes.PieChart.Paint(ChartGraphics graph, CommonElements common, ChartArea area, Series seriesToDraw)
à System.Windows.Forms.DataVisualization.Charting.ChartArea.Paint(ChartGraphics graph)
à System.Windows.Forms.DataVisualization.Charting.ChartPicture.Paint(Graphics graph, Boolean paintTopLevelElementOnly)
à System.Windows.Forms.DataVisualization.Charting.Chart.OnPaint(PaintEventArgs e)
à System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
à System.Windows.Forms.Control.WmPaint(Message& m)
à System.Windows.Forms.Control.WndProc(Message& m)
à System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
à System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
à System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
答案 0 :(得分:0)
您可以从Chart控件创建派生类以处理异常:
public class ChartEx : Chart
{
public event EventHandler CustomEvent;
protected override void OnPaint(PaintEventArgs e)
{
try
{
base.OnPaint(e);
}
catch (InvalidOperationException ex)
{
if (CustomEvent != null)
{
CustomEvent(this, e);
}
}
}
}
在主类中处理事件。