【问题标题】:How to mark last row in DataGridView in case of vertical scroll bar?在垂直滚动条的情况下如何标记DataGridView中的最后一行?
【发布时间】:2013-09-21 09:33:35
【问题描述】:

我尝试过MyDataGridView.Rows[index].Selected = true;,但这标记了所有行。

我想要的是在垂直滚动条的情况下我想看到最后一行而不需要手动操作

这不起作用,因为像 Selected property 它标记了所有行:

        int last = DataGridView.Rows.Count;
        last = DataGridView.FirstDisplayedScrollingRowIndex;

这是我的添加项目功能:

    private void AddToDataGridView(MyObject obj)
    {
        this.Invoke((MethodInvoker)delegate
        {
            int index = dataGridView.Rows.Add(
                obj.machineIpAddress,
                obj.fileSize,
                obj.fileName,
                obj.processId,
                DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
                "Start...");
            dataGridView.Rows[index].Cells[5].Style.BackColor = Color.SkyBlue;
            ColorRow(index, obj.fileSize);
            dataGridView.CurrentCell.Selected = false;
            var lastRow = dataGridView.Rows[dataGridView.Rows.Count - 1];
            lastRow.Selected = true;
            dataGridView.FirstDisplayedCell = lastRow.Cells[0];
        });
    }

此函数聚焦最后一行,但选中了 DataGridView 中的所有行

【问题讨论】:

  • 如果您打算将最后一行滚动到 datagridview 的可见部分,请使用 FirstDisplayedScrollingRowIndex 属性并将最后一行的索引分配给它。
  • 再次标记所有行,而不仅仅是最后一行
  • 当您在问题中使用编辑后的代码时,您就搞错了。任务应该是相反的。如果您标记了行,那么这来自此处未显示的不同代码。

标签: c# winforms datagridview


【解决方案1】:

试试这个:

dataGridView1.CurrentCell.Selected = false;
var lastRow = dataGridView1.Rows[dataGridView1.Rows.Count - 1];
//de-select the last selected rows;
dataGridView1.SelectedRows.OfType<DataGridViewRow>().ToList().ForEach(x=>x.Selected=false);
lastRow.Selected = true;
dataGridView1.FirstDisplayedCell = lastRow.Cells[0];

【讨论】:

  • @user1860934 这对我有用,你想要的实际行为是什么?有截图吗?
  • 我只想标记/选择我的 DataGridView 中的最后一行,实际上它标记了每行添加后的所有行
  • @user1860934 但是我测试了代码并且它适用于我,你应该展示你测试过的代码。
  • @user1860934 为什么你必须使用Invoke?看起来这里涉及到一些threading stuff。您发布的代码只是添加行的代码,但您何时调用该方法?了解这一点很重要。
  • 没有调用我得到跨线程,因为我的应用程序打开了几个线程,为什么这很重要?
猜你喜欢
  • 2019-12-09
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
相关资源
最近更新 更多