如何阻止DataGridView
控件在我已经消耗了第一个之后触发每个选定行的UserDeletingRow
- 事件?
这个网格绑定到我的wcf-webservice中的对象,我想只对所有应删除的对象执行一次delete方法。
为每个选定的行触发此事件处理程序,该行也始终触发“你真的要删除”-messageboxes:
private void Grid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
switch (this.Type)
{
case AdminType.Channel:
List<Channel> channels = GrdChannel.SelectedRows.Cast<DataGridViewRow>()
.Select(row => (Channel)row.DataBoundItem).ToList();
e.Cancel = !Delete_Channels(channels);
break;
// other types ...
default:
break;
}
}
此方法在确认后调用Web服务:
private bool Delete_Channels(List<Channel> channels)
{
var msg = string.Format("Do you really want to delete {0}?", channels.Count == 1 ? "this channel" : "these channels");
var title = channels.Count == 1 ? "Delete channel" : "Delete channels";
bool yes = MessageBox.Show(msg, title, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes;
if (yes)
{
using (var db = new ERP_ServiceClient())
db.DeleteChannels(channels, this.IdUser);
string message = string.Format("{0} deleted successfully: {1}"
, channels.Count == 1 ? "Channel" : "Channels"
, string.Join(",", channels.Select(p => p.Name)));
channelBindingSource.Remove(channels);
Main.ShowStatusMessage(message);
}
return yes;
}
答案 0 :(得分:1)
好吧,显然没有更好的方法(就可读性而言)所以我已经实现了Tigrans建议在事件处理程序中使用count变量,并且只在最后一个选定行触发此事件后才开始删除。
以下是解决方法:
private int _deleteCount = 0;
private bool _deleting = false;
private bool _reallyDelete = false;
private IEnumerable<object> _deleteEntities = null;
private void Grid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
DataGridView grid = (DataGridView)sender;
if (!_deleting)
{
_deleting = true;
_deleteCount = grid.SelectedRows.Count;
_deleteEntities = grid.SelectedRows.Cast<DataGridViewRow>().Select(r => r.DataBoundItem).ToList();
string msg = "";
string title = "";
switch (this.Type)
{
case AdminType.Channel:
msg = string.Format("Do you really want to delete {0}?", _deleteCount == 1 ? "this channel" : "these channels");
title = _deleteCount == 1 ? "Delete channel" : "Delete channels";
break;
// other types ...
default:
break;
}
_reallyDelete = MessageBox.Show(msg, title, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes;
}
e.Cancel = !_reallyDelete;
// wait until all events are triggered before starting to delete
if (--_deleteCount == 0)
{
switch (this.Type)
{
case AdminType.Channel:
List<Channel> channels = _deleteEntities.Cast<Channel>().ToList();
Delete_Channels(channels);
break;
// other types ...
default:
break;
}
_deleting = false;
_reallyDelete = false;
_deleteEntities = null;
}
}
答案 1 :(得分:0)
使用此事件key_Down
替换UserDeletingRow的事件if(e.KeyValue == 46)//删除密钥
{ e.Handled = MessageBox.Show(&#34;你真的要删除选中的行&#34;, &#34;确认&#34;,MessageBoxButtons.OKCancel,MessageBoxIcon.Question)!= DialogResult.OK; }