ErrorText和ContextMenuStrip之间的交互
本文关键字:交互 之间 ContextMenuStrip ErrorText | 更新日期: 2023-09-27 17:59:21
我的应用程序有一个带有RowValidating事件处理程序的datagridview。如果我在RowValidating中设置了ErrorText
,它正确地禁止左键单击其他行和其他控件,但如果我将ContextMenuStrip分配给另一个控件,ContextMenuStap将保持活动状态。用户可以用上下文菜单右键单击控件,选择一个菜单项,菜单事件就会启动。
我已经尝试了各种事件处理,但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
处理ToolStripDropDown。打开事件,通过设置e.Cancel
来确定上下文菜单是否应该显示。或者您可以禁用菜单项。