2016-10-19 1 views
0

Пожалуйста, помогите мне найти источник этой ошибки:DataGridView System.IndexOutOfRangeException: Индекс 0 не имеет значения при закрытии формы

Error happened Display: System.IndexOutOfRangeException: Index 0 does not have a value. 
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index) 
at 
System.Windows.Forms.DataGridview.DataGridViewDataConnection.GetError(Int32 rowIndex) 

Эта ошибка появляется только тогда, когда Im закрытии формы и обыкновение уходить. Индекс 0 просто продолжает увеличиваться каждый раз, когда я нажимаю OK.

При загрузке формы не возникает никаких проблем.

Вот весь мой код:

public partial class frmSalesOrders : Form 
{ 
    public frmSalesOrders() 
    { 
     InitializeComponent(); 
    } 

    private void frmSalesOrders_Load(object sender, EventArgs e) 
    { 

     this.Enabled = false; 
     this.usersTableAdapter.Fill(this.dsSalesOrders.users); 
     this.companiesTableAdapter.Fill(this.dsSalesOrders.companies); 
     this.salesordersTableAdapter.Fill(this.dsSalesOrders.salesorders); 
     this.Enabled = true; 
    } 

    private void btnSOFilter_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      string key = tbSOFilterKey.Text; 
      int custid = Convert.ToInt32(cbSOFilterByCustomer.SelectedValue); 
      string startdate = dtpSOFilterStartDate.Value.ToShortDateString(); 
      string enddate = dtpSOFilterEndDate.Value.ToShortDateString(); 
      salesordersBindingSource.Filter = string.Format("comp = '{0}' AND (sonumber LIKE '%{1}%' OR ponumber LIKE '%{1}%') AND podate > '{2}' AND podate <'{3}'", custid, key, startdate, enddate); 
     } 
     catch(Exception ex) 
     { 
      DialogResult res = MessageBox.Show(ex.Message, "Exception Error on Filter of Sales Orders", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); 
      if(res == DialogResult.Retry) 
      { 
       string key = tbSOFilterKey.Text; 
       int custid = Convert.ToInt32(cbSOFilterByCustomer.SelectedValue); 
       string startdate = dtpSOFilterStartDate.Value.ToShortDateString(); 
       string enddate = dtpSOFilterEndDate.Value.ToShortDateString(); 
       salesordersBindingSource.Filter = string.Format("comp = '{0}' AND (sonumber LIKE '%{1}%' OR ponumber LIKE '%{1}%') AND podate > '{2}' AND podate <'{3}'", custid, key, startdate, enddate); 
      } 
      else 
      { 
       tbSOFilterKey.Clear(); 
      } 
     } 
    } 

    private void btnSOClearFilter_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      tbSOFilterKey.Clear(); 
      cbSOFilterByCustomer.SelectedValue = 0; 
      dtpSOFilterStartDate.Value = Convert.ToDateTime("01/01/1970"); 
      dtpSOFilterEndDate.Value = DateTime.Now; 
      salesordersBindingSource.RemoveFilter(); 
     } 
     catch(Exception ex) 
     { 
      DialogResult res = MessageBox.Show(ex.Message, "Exception Error on Clearing Filter of Sales Orders", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); 
      if (res == DialogResult.Retry) 
      { 
       tbSOFilterKey.Clear(); 
       cbSOFilterByCustomer.SelectedValue = 0; 
       dtpSOFilterStartDate.Value = Convert.ToDateTime("01/01/1970"); 
       dtpSOFilterEndDate.Value = DateTime.Now; 
       salesordersBindingSource.RemoveFilter(); 
      } 
      else 
      { 
       return; 
      } 
     } 
    } 

    private void btnCancelChanges_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      salesordersBindingSource.CancelEdit(); 
      formatOrderAmt(); 
     } 
     catch(Exception ex) 
     { 
      DialogResult res = MessageBox.Show(ex.Message, "Exception Error on Cancellation of Changes to Sales Orders", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); 
      if(res == DialogResult.Retry) 
      { 
       salesordersBindingSource.CancelEdit(); 
       formatOrderAmt(); 
      } 
      else 
      { 
       return; 
      } 
     } 
    } 

    private void btnSaveChanges_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      cbSOLastModBy.SelectedValue = UserDetails.userid; 
      tbSOLastModOn.Text = DateTime.Now.ToString(); 

      int rowIndex = dGridSalesOrdersList.CurrentCell.RowIndex; 

      this.Cursor = Cursors.WaitCursor; 
      this.Enabled = false; 

      this.Validate(); 
      this.salesordersBindingSource.EndEdit(); 
      this.salesordersTableAdapter.Update(dsSalesOrders.salesorders); 
      this.salesordersTableAdapter.Fill(dsSalesOrders.salesorders); 

      this.dGridSalesOrdersList.ClearSelection(); 
      this.dGridSalesOrdersList.Rows[rowIndex].Selected = true; 

      this.Enabled = true; 
      this.Cursor = Cursors.Default; 
     } 
     catch(Exception ex) 
     { 
      DialogResult res = MessageBox.Show(ex.Message, "Exception Error on Saving of Changes to Sales Orders", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); 
      if (res == DialogResult.Retry) 
      { 
       cbSOLastModBy.SelectedValue = UserDetails.userid; 
       tbSOLastModOn.Text = DateTime.Now.ToString(); 

       int rowIndex = dGridSalesOrdersList.CurrentCell.RowIndex; 

       this.Cursor = Cursors.WaitCursor; 
       this.Enabled = false; 

       this.Validate(); 
       this.salesordersBindingSource.EndEdit(); 
       this.salesordersTableAdapter.Update(dsSalesOrders.salesorders); 
       this.salesordersTableAdapter.Fill(dsSalesOrders.salesorders); 

       this.dGridSalesOrdersList.ClearSelection(); 
       this.dGridSalesOrdersList.Rows[rowIndex].Selected = true; 

       this.Enabled = true; 
       this.Cursor = Cursors.Default; 
      } 
      else 
      { 
       this.salesordersBindingSource.CancelEdit(); 
      } 
     } 
    } 

    private void btnSONew_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      this.dGridSalesOrdersList.ClearSelection(); 
      DataRowView drv = (DataRowView) salesordersBindingSource.AddNew(); 
      drv["sonumber"] = "Auto"; 
      drv["status"] = false; 
      drv["cancelled"] = false; 
      drv["podate"] = DateTime.Now; 
      drv["orderamt"] = 0; 
      drv["createdby"] = UserDetails.userid; 
      drv["createdon"] = DateTime.Now; 
      drv["lastmodby"] = UserDetails.userid; 
      drv["lastmodon"] = DateTime.Now; 
      this.dGridSalesOrdersList.CurrentCell.Selected = true; 

     } 
     catch(Exception ex) 
     { 
      DialogResult res = MessageBox.Show(ex.Message, "Exception Error on Adding New Sales Orders", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); 
      if (res == DialogResult.Retry) 
      { 
       this.dGridSalesOrdersList.ClearSelection(); 
       DataRowView drv = (DataRowView)salesordersBindingSource.AddNew(); 
       drv["sonumber"] = "Auto"; 
       drv["status"] = false; 
       drv["cancelled"] = false; 
       drv["podate"] = DateTime.Now; 
       drv["orderamt"] = 0; 
       drv["createdby"] = UserDetails.userid; 
       drv["createdon"] = DateTime.Now; 
       drv["lastmodby"] = UserDetails.userid; 
       drv["lastmodon"] = DateTime.Now; 
       this.dGridSalesOrdersList.CurrentCell.Selected = true; 
      } 
      else 
      { 
       this.salesordersBindingSource.CancelEdit(); 
      } 
     } 
    } 

    private void frmSalesOrders_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     try 
     { 
      this.salesordersBindingSource.CancelEdit(); 
     } 
     catch (Exception ex) 
     { 
      DialogResult res = MessageBox.Show(ex.Message, "Exception Error on Closing Form", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); 
      if (res == DialogResult.Retry) 
      { 
       this.salesordersBindingSource.CancelEdit(); 
      } 
      else 
      { 
       this.salesordersBindingSource.CancelEdit(); 
      } 
     } 
    } 

    private void btnSOViewMoreDetails_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      this.Cursor = Cursors.WaitCursor; 
      this.Enabled = false; 
      soSelected.soid = Convert.ToInt32(tbSOSequence.Text); 
      frmSODetails soDetails = new frmSODetails(); 
      soDetails.ShowDialog(); 
      this.Cursor = Cursors.WaitCursor; 
      this.salesordersTableAdapter.Fill(this.dsSalesOrders.salesorders); 
      this.Enabled = true; 
      this.Cursor = Cursors.Default; 
     } 
     catch (Exception ex) 
     { 
      DialogResult res = MessageBox.Show(ex.Message, "Exception Error on Viewing Sales Order Details", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); 
      if (res == DialogResult.Retry) 
      { 
       this.Cursor = Cursors.WaitCursor; 
       this.Enabled = false; 
       soSelected.soid = Convert.ToInt32(tbSOSequence.Text); 
       frmSODetails soDetails = new frmSODetails(); 
       soDetails.ShowDialog(); 
       this.Cursor = Cursors.WaitCursor; 
       this.salesordersTableAdapter.Fill(this.dsSalesOrders.salesorders); 
       this.Enabled = true; 
       this.Cursor = Cursors.Default; 
      } 
      else 
      { 
       frmSODetails soDetails = new frmSODetails(); 
       soDetails.Close(); 
      } 
     } 
    } 

    private void formatOrderAmt() 
    { 
     if(tbSOPOAmount.TextLength > 0) 
     { 
      decimal amount = Convert.ToDecimal(tbSOPOAmount.Text); 
      tbSOPOAmount.Text = string.Format("{0:#,##0.00}", double.Parse(amount.ToString())); 
     } 
     else 
     { 
      tbSOPOAmount.Text = string.Format("{0:#,##0.00}", double.Parse("0.00")); 
     } 

    } 

    private void dGridSalesOrdersList_DataError(object sender, DataGridViewDataErrorEventArgs anError) 
    { 
     MessageBox.Show("Error happened " + anError.Context.ToString() + " : "+ anError.Exception.ToString()); 

     if (anError.Context == DataGridViewDataErrorContexts.Commit) 
     { 
      MessageBox.Show("Commit error"); 
     } 
     if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange) 
     { 
      MessageBox.Show("Cell change"); 
     } 
     if (anError.Context == DataGridViewDataErrorContexts.Parsing) 
     { 
      MessageBox.Show("parsing error"); 
     } 
     if (anError.Context == DataGridViewDataErrorContexts.LeaveControl) 
     { 
      MessageBox.Show("leave control error"); 
     } 

     if ((anError.Exception) is ConstraintException) 
     { 
      DataGridView view = (DataGridView)sender; 
      view.Rows[anError.RowIndex].ErrorText = "an error"; 
      view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error"; 

      anError.ThrowException = false; 
     } 
    } 

    private void dGridSalesOrdersList_SelectionChanged(object sender, EventArgs e) 
    { 
     //formatOrderAmt(); 
    } 
} 

ответ

0

Отказ от ответственности: Я не уверен, если это действительно решает проблему или просто QuickFix.

Я попытался реализовать одно предложение от MSDN Forum, которое должно утилизировать DataGridView и BindingSource при событии Form_Closed, и ошибка исчезла.

Код:

private void frmSalesOrders_FormClosed(object sender, FormClosedEventArgs e) 
    { 
     usersBindingSourceSOCreatedBy.Dispose(); 
     usersBindingSourceSOLastModBy.Dispose(); 
     companiesBindingSource.Dispose(); 
     salesordersBindingSource.Dispose(); 
     dGridSalesOrdersList.Dispose(); 
    } 
Смежные вопросы