在DataGridViewCell中捕捉KeyUp事件
本文关键字:KeyUp 事件 DataGridViewCell | 更新日期: 2023-09-27 17:54:31
我正在为DataGridView
的特定列中的所有单元格制作自动完成行为。
我已经找了好几个小时了,但是没有找到任何有用的方法。
有许多事件,例如当用户单击其中一个时,当用户在DataGridView
中keyup时(被调用的次数太多),等等。但是在Cell中没有KeyUp事件。
有什么办法吗?
你可以尝试在列内使用模板字段和文本框然后在上面使用keyup ?
您可以使用datagridview文本框列并设置其自动完成源
http://social.msdn.microsoft.com/forums/en us/winformsdatacontrols/thread/276e8f89 - 5 - cef - 4208 a4be - 08 - f4000bd753/
像这样,
AutoCompleteStringCollection scAutoComplete = new AutoCompleteStringCollection();
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strConn = "Server = .;Database = NorthWind; Integrated Security = SSPI;";
SqlConnection conn = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("Select * from [Order Details]", conn);
da.Fill(dt);
dataGridView1.DataSource = dt;
for (int x = 1; x <= 61000; x++ )
{
scAutoComplete.Add(x.ToString());
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCellAddress.X == 1)
{
TextBox txt = e.Control as TextBox;
txt.AutoCompleteCustomSource = scAutoComplete;
txt.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txt.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if(e.ColumnIndex==1)
{
if(!scAutoComplete.Contains(e.FormattedValue.ToString()))
{
MessageBox.Show("Invalid Data");
e.Cancel=true;
}
}
}
这对我来说是有效的(对于一个按键,同样应该是一个键的上下):
Private dgTextbox As TextBox = New TextBox
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
RemoveHandler dgTextbox.KeyPress, AddressOf dgTextbox_KeyPress
dgTextbox = CType(e.Control, TextBox)
AddHandler dgTextbox.KeyPress, AddressOf dgTextbox_KeyPress
End Sub
Private Sub dgTextbox_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
'your code goes here
End Sub