互联网上有答案,但它不起作用,我想知道我做错了什么。
我有DataGridView
一列,Column1
。这是列的名称,而不是文本或其他任何内容。
private void InitializeComponent()
{
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.SuspendLayout();
//
// dataGridView1
//
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1});
this.dataGridView1.Name = "dataGridView1";
//
// Column1
//
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
.....
}
public Form1()
{
InitializeComponent();
// Works
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "AAAAA";
dataGridView1.Rows.Add(row);
// Fails
row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells["Column1"].Value = "AAAAA"; // Argument Exception: "Column named Column1 cannot be found"
dataGridView1.Rows.Add(row);
}
请解释一下?非常感谢你!
答案 0 :(得分:2)
该行不是Datagridview的一部分,因此无法找到该列。将其添加回datagridview FIRST,然后使用列名称为其分配值,或者按列的索引对单元格进行寻址:
row.Cells[dataGridView1.Columns["Column1"].Index].Value = "AAAAA";