我在winforms应用程序中有一个datagridview,带有一个绑定列表数据源。我正在使用bindingnavigator浏览datagridview中的记录。当我单击bindingnavigator上的Delete按钮时,它会抛出几个带有IndexOutOfRangeException的错误对话框。
当我从RowValidating事件中删除GridView_RowValidating处理程序时,它没有发生,但是我不知道为什么抛出异常。我没有向事件添加任何代码,它只是在bindingsource上调用removeCurrent。
public PersonEditor()
{
InitializeComponent();
isClosing = false;
wasSaved = true;
try
{
BindingSource source = new BindingSource(DataFetcher.GetPeople(), null);
gridPeople.DataSource = source;
bindingNavigator1.BindingSource = source;
gridPeople.RowValidating += GridView_RowValidating;
txtRegNr.DataBindings.Add("Text", source, "RegisterNumber", false, DataSourceUpdateMode.OnPropertyChanged);
txtFirstName.DataBindings.Add("Text", source, "FirstName", false, DataSourceUpdateMode.OnPropertyChanged);
txtLastName.DataBindings.Add("Text", source, "LastName", false, DataSourceUpdateMode.OnPropertyChanged);
txtAddress.DataBindings.Add("Text", source, "Address", false, DataSourceUpdateMode.OnPropertyChanged);
txtCity.DataBindings.Add("Text", source, "City", false, DataSourceUpdateMode.OnPropertyChanged);
txtPhone.DataBindings.Add("Text", source, "Phone", false, DataSourceUpdateMode.OnPropertyChanged);
txtZip.DataBindings.Add("Text", source, "ZipCode", false, DataSourceUpdateMode.OnPropertyChanged);
} -- error handling comes below
}
private void GridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
if (!isClosing)
{
var sb = new StringBuilder();
var dg = (DataGridView)sender;
var cells = dg.Rows[e.RowIndex].Cells;
if (cells["RegisterNumber"].Value == null)
{
if (sb.Length == 0) sb.Append("Following fields cannot be empty:");
sb.Append(" registerNumber");
}
if (cells["FirstName"].Value == null)
{
if (sb.Length == 0) sb.Append("Following fields cannot be empty:");
if (sb.Length > 0) sb.Append(",");
sb.Append(" FirstName");
}
if (cells["LastName"].Value == null)
{
if (sb.Length == 0) sb.Append("Following fields cannot be empty:");
if (sb.Length > 0) sb.Append(",");
sb.Append(" LastName");
}
if (cells["Address"].Value == null)
{
if (sb.Length == 0) sb.Append("Following fields cannot be empty:");
if (sb.Length > 0) sb.Append(",");
sb.Append(" Address");
}
if (cells["ZipCode"].Value == null)
{
if (sb.Length == 0) sb.Append("Following fields cannot be empty:");
if (sb.Length > 0) sb.Append(",");
sb.Append(" ZipCode");
}
if (cells["City"].Value == null)
{
if (sb.Length == 0) sb.Append("Following fields cannot be empty:");
if (sb.Length > 0) sb.Append(",");
sb.Append(" City");
}
if (sb.Length > 0)
{
MessageBox.Show(sb.ToString());
btnSave.Enabled = false;
}
else
{
btnSave.Enabled = true;
}
}
}