【问题标题】:DataGridView set CurrentCell not workingDataGridView 设置 CurrentCell 不起作用
【发布时间】:2015-10-18 12:14:18
【问题描述】:

我正在尝试填充 DataGridView 并预选一个单元格。 但它运作不佳。 我正在使用此代码创建DataGridView

DataTable table = new DataTable();
table.Columns.Add("Column1");
table.Columns.Add("Column2");
table.Rows.Add("Row1");
table.Rows.Add("Row2");
table.Rows.Add("Row3");
table.Rows.Add("Row3");
table.Rows.Add("Row4");
table.Rows.Add("");

dataGridView1.DataSource = table;
dataGridView1.ReadOnly = false;
dataGridView1.Columns["Column1"].ReadOnly = true;
dataGridView1[1, 2].ReadOnly = true;
dataGridView1[1, 3].ReadOnly = true;

DataGridViewButtonCell button = new DataGridViewButtonCell();
dataGridView1[1, table.Rows.Count - 1] = button;
button.Value = "Go";
button.FlatStyle = FlatStyle.Flat;

dataGridView1.CurrentCell = dataGridView1[0, 1];

理论上应该选择右侧的第一个单元格,但选择第一列的第三行。 这个问题是否会导致:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{

}

或者

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{

}

?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    你使用以下

    dataGridView1.CurrentCell = dataGridView1[0, 1];
    

    然后说

    理论上应该选择右侧的第一个单元格

    事实上,单元格索引器的参数是columnIndex, rowIndex,所以上面应该选择第二行的第一列,确实如此。如果您打算选择第一行的第二列,请使用dataGridView[1, 0]

    【讨论】:

    • 我已经测试过 dataGridView1.CurrentCell = dataGridView1[0, 0];但是选择了第二列和第二行。就好像他不知道第一排一样。
    • @ComanderKai77 上面的方法什么时候执行——表单构造函数,加载事件还是?
    • 在 Form1_Load 我用你的意思这个代码调用方法。
    • @ComanderKai77 好吧,我已经完全尝试了您发布的代码,并且它按预期工作 - 在表单加载事件中,它完全选择了我指定的单元格。确保您没有从选择另一个单元格的网格事件中执行一些其他代码。
    • 谢谢,我发现了这个bug。
    【解决方案2】:

    当您要设置dataGridView1.CurrentCell 时,应注意dataGridView1[0, 1] 中的第一个数字是columnIndex,第二个数字是rowIndex。所以如果你想选择右侧的第一个单元格,你应该试试这个:

    dataGridView1.CurrentCell = dataGridView1[1,0];//first row second column
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2013-01-15
      相关资源
      最近更新 更多