我的应用程序有一个带有RowValidating事件处理程序的datagridview。如果我在RowValidating中设置ErrorText
,它会正确地禁止左键单击其他行和其他控件,但如果我将ContextMenuStrip分配给另一个控件,则ContextMenuStrip将保持活动状态。用户可以使用上下文菜单右键单击控件,选择菜单项,然后触发菜单事件。
我已尝试过各种事件处理,但RowValidating事件在菜单出现之前并未触发,因此我无法在RowValidating中禁用上下文菜单。我可以在用户触摸网格的任何部分时禁用上下文菜单,但这有其他陷阱......
我看过,我没有看到微软缺陷或变通办法上的任何现有文章,甚至是其他遇到错误的人,所以我不确定我做错了什么
简化示例:
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.menuItemToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.textBox1 = new System.Windows.Forms.TextBox();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1});
this.dataGridView1.RowValidating += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.dataGridView1_RowValidating);
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.menuItemToolStripMenuItem});
this.menuItemToolStripMenuItem.Text = "Menu Item";
this.textBox1.ContextMenuStrip = this.contextMenuStrip1;
this.Controls.Add(this.textBox1);
this.Controls.Add(this.dataGridView1);
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem menuItemToolStripMenuItem;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
if (!RowValid(dataGridView1.Rows[e.RowIndex]))
{
dataGridView1.Rows[e.RowIndex].ErrorText = "Value must be 5";
e.Cancel = true;
}
else
{
dataGridView1.Rows[e.RowIndex].ErrorText = string.Empty;
e.Cancel = false;
}
}
private bool RowValid(DataGridViewRow row)
{
return string.Equals(row.Cells[0].Value, "5");
}
作为参考,这些是按顺序触发的事件,在菜单打开之前不会发生注释验证:
dataGridView1_Enter
dataGridView1_RowEnter
dataGridView1_CellEnter
dataGridView1_CellBeginEdit
contextMenuStrip1_Opening