在一个 Windows 窗体中,用下面的代码加入一个 DataGrid:private void Form4_Load(object sender, System.EventArgs e) {
DataGrid dataGrid = new DataGrid();
dataGrid.CaptionVisible = false;
dataGrid.Dock = DockStyle.Fill;

DataTable table = new DataTable("MyTable");
table.Columns.Add( "id", typeof(int) );
table.Columns.Add( "name", typeof(string) );
table.Columns.Add( "address", typeof(string) );

table.RowChanging += new DataRowChangeEventHandler(this.table_RowChanging);
dataGrid.DataSource = table;

this.Controls.Add(dataGrid);
}

private void table_RowChanging(object sender, DataRowChangeEventArgs e) {
MessageBox.Show(true.ToString());
}程序运行后,当 DataGrid 的行发生变化时,MessageBox.Show 方法会抛出异常,并且异常信息非常怪,信息好象是 DataGrid 或是 DataTable 的错误。但是如果这条语句放到别的事件里却不会有异常。

解决方案 »

  1.   

    异常信息:
    System.IndexOutOfRangeException: 索引 0 处没有值。
    at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)异常与 true.ToString() 无关,改成下面这样照样有异常:
    private void table_RowChanging(object sender, DataRowChangeEventArgs e)
    {
      MessageBox.Show("OK");
    }
      

  2.   

    ************** 异常文本 **************
    System.IndexOutOfRangeException: 索引 0 处没有值。
    at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
    at System.Windows.Forms.DataGridRow.PaintHeader(Graphics g, Rectangle visualBounds, Boolean alignToRight, Boolean rowIsDirty)
    at System.Windows.Forms.DataGridRelationshipRow.PaintHeaderInside(Graphics g, Rectangle bounds, Brush backBr, Boolean alignToRight, Boolean isDirty)
    at System.Windows.Forms.DataGridRelationshipRow.PaintHeader(Graphics g, Rectangle bounds, Boolean alignToRight, Boolean isDirty)
    at System.Windows.Forms.DataGrid.PaintRows(Graphics g, Rectangle& boundingRect)
    at System.Windows.Forms.DataGrid.PaintGrid(Graphics g, Rectangle gridBounds)
    at System.Windows.Forms.DataGrid.OnPaint(PaintEventArgs pe)
    at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
    at System.Windows.Forms.Control.WmPaint(Message& m)
    at System.Windows.Forms.Control.WndProc(Message& m)
    at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)
    at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)
    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)好象是重绘 DataGrid 时发生的异常.
      

  3.   

    "wuyi8808(tm) studio 2005  :) " 说得没错,是这个事件和 DataGrid 结合的时候,如果在事件处理程序里不能有 MessageBox.Show。这个异常很奇怪啊,不知道MS的工程师会有什么说法。