如何在DatagridView中显示空格键按下事件的列表框
本文关键字:事件 列表 空格键 DatagridView 显示 | 更新日期: 2023-09-27 18:13:13
在我的Winform应用程序中有一个DataGrid视图(dataGridView1)和2个列表框,listBox1和listBox2。在dataGridView1中,有三列,Column1 (id), Column2 (Category)和Column3 (Items)。我想显示listBox1,当用户按空格键时包含类别,并且在按回车键后应该关注Items列。
我找到了一些解决方案,但没有达到我的要求。比如, If (spacebar is pressed && dataGridView1.CurrentCell.ColumnIndex== 2)
{
listbox1.Visible = true;
listbox1.Focus();
listbox1.SelectedIndex = 0;
}
我不能给你看我的表单图片,因为我的声誉很低。
感谢大家!
这是一个很长的时间,因为我已经使用了一个datagridview,但如果你检查它的事件,我认为你有一个CellEnter和一个CellLeave事件,你可以用来检查哪一列被选中和修改你的列表视图的可见属性。
CellEnter的事件处理程序有一个列索引参数来帮助您。
at datagridview的keydown事件
if (e.KeyCode == Keys.Space)//check if space is pressed
{
if(dataGridView1.CurrentCell.ColumnIndex== 2)
{
listbox1.Visible = true;
listbox1.Focus();
}
}
要检查输入键,请在datagrid的keydown事件中使用这个
if (e.KeyCode == Keys.Enter) //if enter key is pressed change selected index
{
listbox1.SelectedIndex = 3;
}
在第0列(id)中,未编辑,按回车键并移动下一个单元格:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter && dataGridView1.CurrentCell.ColumnIndex == 0)
{
dataGridView1.CurrentCell = dataGridView1[1, dataGridView1.CurrentCell.ColumnIndex];
}
}
在第0列(id)中,编辑,按回车键并移动下一个单元格(从这里回答):
private int currentRow;
private bool resetRow = false;
void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (resetRow)
{
resetRow = false;
dataGridView1.CurrentCell = dataGridView1.Rows[currentRow].Cells[1];
}
}
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
resetRow = true;
currentRow = e.RowIndex;
}
*注意:您可能需要在完成绑定数据到datagridview后绑定SelectionChanged
事件,而不是在设计时绑定。
在第1列(猫)和第2列(项目)中,按空格键显示列表猫和列表项目:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1)
((TextBox)e.Control).KeyPress += new KeyPressEventHandler(col1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 2)
((TextBox)e.Control).KeyPress += new KeyPressEventHandler(col2_KeyPress);
}
void col1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 32)
{
listBox1.Visible = true;
listBox1.Focus();
listBox1.SelectedIndex = 0;
}
}
void col2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 32)
{
listBox2.Visible = true;
listBox2.Focus();
listBox2.SelectedIndex = 0;
}
}