单元格值更改时在 DataGridView 上显示工具提示
Show ToolTip on DataGridView when cell value has changed
我想在 DataGridView
控件中的单元格值更改且引入的值无效时显示 ToolTip
。
下面的代码可以很容易的做到,但是问题是ToolTip
显示后,它也和控件关联,所以每次DataGridView
悬停时ToolTip
显示,我希望它在数据更改后只显示一次。
我注意到只有 DataGridView
和 GroupBox
才会出现这种情况。对于 TextBox
或 Button
,ToolTip
在其上方显示时与控件无关。
为什么会这样?
public partial class Form1 : Form
{
this.dataGridView1.ShowCellToolTips = false; // so we can show regular tooltip
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView control = (DataGridView)sender;
// check if control.Rows[e.RowIndex].Cells[e.ColumnIndex].Value is valid
if (invalid)
{
toolTip.Show("Invalid data", dataGridView1, 5000);
}
}
有很多方法可以解决这个问题。最简单和最直接的似乎是 Hide
离开 DataGridView
时的 ToolTip
:
private void dataGridView1_Leave(object sender, EventArgs e)
{
toolTip1.Hide(this);
}
当然,当错误仍然存在时,应该由您来决定应该发生什么的完整设计..!
至于Textboxes
:他们很特别,通常问他们为什么表现不同是没有用的..
另一种方法是对 Popup 事件进行编码并使用 Tag 作为标志以确保它只显示一次:
在 CellValueChanged 中显示它之前,您设置了一个标志:
toolTip1.Tag = "true";
并在 Popup 事件中检查它:
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
if (toolTip1.Tag == null) return;
bool show = toolTip1.Tag.ToString() == "true";
if (toolTip1.Tag != "true") e.Cancel = true;
toolTip1.Tag = "false";
}
我想在 DataGridView
控件中的单元格值更改且引入的值无效时显示 ToolTip
。
下面的代码可以很容易的做到,但是问题是ToolTip
显示后,它也和控件关联,所以每次DataGridView
悬停时ToolTip
显示,我希望它在数据更改后只显示一次。
我注意到只有 DataGridView
和 GroupBox
才会出现这种情况。对于 TextBox
或 Button
,ToolTip
在其上方显示时与控件无关。
为什么会这样?
public partial class Form1 : Form
{
this.dataGridView1.ShowCellToolTips = false; // so we can show regular tooltip
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView control = (DataGridView)sender;
// check if control.Rows[e.RowIndex].Cells[e.ColumnIndex].Value is valid
if (invalid)
{
toolTip.Show("Invalid data", dataGridView1, 5000);
}
}
有很多方法可以解决这个问题。最简单和最直接的似乎是 Hide
离开 DataGridView
时的 ToolTip
:
private void dataGridView1_Leave(object sender, EventArgs e)
{
toolTip1.Hide(this);
}
当然,当错误仍然存在时,应该由您来决定应该发生什么的完整设计..!
至于Textboxes
:他们很特别,通常问他们为什么表现不同是没有用的..
另一种方法是对 Popup 事件进行编码并使用 Tag 作为标志以确保它只显示一次:
在 CellValueChanged 中显示它之前,您设置了一个标志:
toolTip1.Tag = "true";
并在 Popup 事件中检查它:
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
if (toolTip1.Tag == null) return;
bool show = toolTip1.Tag.ToString() == "true";
if (toolTip1.Tag != "true") e.Cancel = true;
toolTip1.Tag = "false";
}