【问题标题】:Windows Form: change dataGridView's first cell origin?Windows 窗体:更改 dataGridView 的第一个单元格原点?
【发布时间】:2015-06-11 15:59:30
【问题描述】:

长话短说,我有这个 dataGridView,我希望单元格 [0,0] 成为网格左下角的单元格,而不是像默认情况下那样位于网格的左上角。

例如,在视觉上,如果我执行以下操作:

dataGridView1[0, 0].Value = "a";

I get this (sorry not enough reputation to post pictures)

但我希望通过执行相同的指令,在蓝色突出显示的插槽处出现“a”,并通过添加行之类的操作将其添加到网格的顶部。

非常感谢和问候

【问题讨论】:

  • 听起来不是一个经过深思熟虑的想法。如果您想在前面添加,只需执行 Insert !

标签: c# winforms matrix datagridview


【解决方案1】:

像这样创建一个类:

public class MyDataGridView : DataGridView
{
    public new DataGridViewCell this[int col, int invertRow]
    {
        get
        {
            int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1);
            return this.Rows[recordCount - invertRow].Cells[col];
        }
        set
        {
            int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1);
            this.Rows[recordCount - invertRow].Cells[col] = value;
        }
    }
}

然后这样称呼它:

dataGridView1[0, 0].Value = "a";

或者,如果您只想设置或获取网格左上角的第一个单元格,则可以使用 FirstDisplayedCell 属性。

MSDN:获取或设置DataGridView当前显示的第一个单元格;通常,此单元格位于左上角。

例如:

dataGridView1.FirstDisplayedCell.Value = "a";

【讨论】:

  • 天哪,对不起,我想他想获取任何索引!我尽快修好了
  • 我通过反转行索引来修复。
  • 好吧,这并不能真正满足 OP 的要求。 Quote: 通过添加行之类的操作,它将被添加到网格的顶部。
  • 我最终会解决这个问题的,TaW。还是太糟糕了,winform 没有这个功能。顺便说一句,谢谢,您的方法效果很好:D
  • @Behzad Khosravifar 现在它在倒数第二行添加元素(例如:如果我把 [0,0] 放在应该是 [0,1] 的位置)。仍然减去 1 似乎工作得很好,所以不要担心:D PS:关于添加行:我不知道插入可以以这种方式使用(我总是以另一种方式使用它)所以我不知道它非常适合我的问题(因此我在理论上从未遇到过)
【解决方案2】:

如果不扩展类,没有本地方法可以做你想做的事,但你可以使用扩展方法来为你反转行索引:

public static DataGridViewCell FromLowerLeft(this DataGridView dgv, int columnIndex, int invertedRowIndex)
{
    return dgv[columnIndex, dgv.RowCount - invertedRowIndex];
} 

这可以用作

dataGridView.FromLowerLeft(0,0).Value = "a";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多