我有一个DataGridView,它的第一列样式设置为ComboBox,而不是默认的TextBox。由于在启动时DataGridView中的行数不是固定的,因此添加新行时,我无法将数据加载到每一行的ComboBoxes中。因此,我尝试加载用户在DataGridView中添加一行的事件:
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
// Identifiers used are:
var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
var myDataTable = myTableAdapter.GetData();
int rowIndex = myDataGridView.CurrentcellAddress.Y;
var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
string itemToAdd;
// Load in the data from the data table
foreach (System.Data.DataRow row in myDataTable.Rows)
{
// Get the current item to be added
itemToAdd = row[0].ToString();
// Make sure there are no duplicates
if (!comboBoxCell.Items.Contains(itemToAdd))
{
comboBoxCell.Items.Add(itemToAdd)
}
}
}
但这仅允许用户单击秒后看到下拉选项。我希望用户只单击一次组合框即可看到选项,而不是不太直观的双击。该怎么办?
答案 0 :(得分:1)
该单元格必须获得焦点才能出现下拉菜单,因此双击实际上是单击即可获得对该单元格的焦点 ,第二次单击即是导致下拉发生。因此,了解如何在this link之后更改焦点。我能够用一行代码修改代码
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
// Identifiers used are:
var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
var myDataTable = myTableAdapter.GetData();
int rowIndex = myDataGridView.CurrentcellAddress.Y;
var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
string itemToAdd;
// Load in the data from the data table
foreach (System.Data.DataRow row in myDataTable.Rows)
{
// Get the current item to be added
itemToAdd = row[0].ToString();
// Make sure there are no duplicates
if (!comboBoxCell.Items.Contains(itemToAdd))
{
comboBoxCell.Items.Add(itemToAdd)
}
}
// Send the focus to the next combo box (removes need for a double click)
myDataGridView.CurrentCell = myDataGridView.Rows[rowIndex + 1].Cells[0]; // <--- HERE
}