gpt4 book ai didi

c# - 添加第二个 DatagridViewRow 导致克隆

转载 作者:太空宇宙 更新时间:2023-11-03 11:28:03 24 4
gpt4 key购买 nike

我遇到了一个有趣的问题。当我只将一个 DataGridViewRow 添加到 DataGridView 时,一切都按预期工作:DataGridView.Rows[0] 是添加的行。当我以某种方式添加第二个 DataGridviewRow 时,不再添加实际的 DataGridViewRows,而是添加克隆。看起来完全相同但实际上不是同一对象的克隆。

所以我想知道这是为什么,这种行为从何而来,如果可能的话如何阻止添加克隆而不是实际行。我查看了带有 Reflector 的 DataGridViewRowCollection 的代码,但找不到任何可疑的东西 - 但也许我错过了一些东西。

这是一个复制问题的代码示例:

DataGridView dgv = new DataGridView { AllowUserToAddRows = false };

DataGridViewTextBoxColumn dgColumn = new DataGridViewTextBoxColumn();
dgv.Columns.Add(dgColumn);

DataGridViewRow drFirst = new DataGridViewRow();
dgv.Rows.Add(drFirst); // Comment this line to showcase the problem

DataGridViewRow drSecond = new DataGridViewRow();
drSecond.Tag = new object();
dgv.Rows.Add(drSecond);

// When drFirst is added this is false - when it isn't this is true (as it should always be?)
bool thisSeemsWrong = object.ReferenceEquals(dgv.Rows[dgv.Rows.Count - 1], drSecond);

// Always true
bool thisSeemsRight = object.ReferenceEquals(dgv.Rows[dgv.Rows.Count - 1].Tag, drSecond.Tag);

最佳答案

Item DataGridViewRowCollection 类的属性创建 GridViewRow 的克隆并返回它,因此 ReferenceEquals 应该始终为 false不止一排。

DataGridViewRow row2 = (DataGridViewRow) dataGridViewRow.Clone();

但如果只有一行且index=0,则返回相同的引用。

if (((index == 0) && (this.items.Count() == 1))) {
dataGridViewRow.IndexInternal = 0;
dataGridViewRow.StateInternal = this.SharedRowState[0];
if (((this.DataGridView != null))) {
this.DataGridView.OnRowUnshared(dataGridViewRow);
}
return dataGridViewRow;
}

这是此属性的完整来源(来自 Reflection):

public DataGridViewRow this[int index]
{
get
{
DataGridViewRow dataGridViewRow = this.SharedRow(index);
if (dataGridViewRow.Index != -1)
{
return dataGridViewRow;
}
if ((index == 0) && (this.items.Count == 1))
{
dataGridViewRow.IndexInternal = 0;
dataGridViewRow.StateInternal = this.SharedRowState(0);
if (this.DataGridView != null)
{
this.DataGridView.OnRowUnshared(dataGridViewRow);
}
return dataGridViewRow;
}
DataGridViewRow row2 = (DataGridViewRow) dataGridViewRow.Clone();
row2.IndexInternal = index;
row2.DataGridViewInternal = dataGridViewRow.DataGridView;
row2.StateInternal = this.SharedRowState(index);
this.SharedList[index] = row2;
int num = 0;
foreach (DataGridViewCell cell in row2.Cells)
{
cell.DataGridViewInternal = dataGridViewRow.DataGridView;
cell.OwningRowInternal = row2;
cell.OwningColumnInternal = this.DataGridView.Columns[num];
num++;
}
if (row2.HasHeaderCell)
{
row2.HeaderCell.DataGridViewInternal = dataGridViewRow.DataGridView;
row2.HeaderCell.OwningRowInternal = row2;
}
if (this.DataGridView != null)
{
this.DataGridView.OnRowUnshared(row2);
}
return row2;
}
}

也许您会在以下文章(从“使用共享行”开始)中找到有关原因的信息:

http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx

关于c# - 添加第二个 DatagridViewRow 导致克隆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com