我在 datagridview 中添加新行时遇到问题

问题描述 投票:0回答:1

添加第一行时,没有问题,但是当尝试添加第二行时,出现错误

不能为负值或超出范围

if (dataGridView1.Rows.Count > 0)  `// التحقق من وجود صفوف قبل إضافة صف جديد`
{
    int nu = dataGridView1.Rows.Count;  `// الحصول على الفهرس الصحيح للصف الجديد`
    dataGridView1.AllowUserToAddRows = true;
    dataGridView1.Rows[nu].Cells[0].Value = dataGridView1.Rows.Count;  `//  Here the problem`   
    dataGridView1.Rows[nu].Cells[6].Value = dt.Tables[0].Rows[0][0];
    dataGridView1.Rows[nu].Cells[1].Value = dt.Tables[0].Rows[0][1];
    dataGridView1.Rows[nu].Cells[3].Value = 1; `// الكمية`
    dataGridView1.Rows[nu].Cells[2].Value = dt.Tables[0].Rows[0][3];
    dataGridView1.Rows[nu].Cells[7].Value = dt.Tables[0].Rows[0][2];
    MessageBox.Show("سطر جديد");
}

如果是这样的话

dataGridView1.Rows[0].Cells[0].Value = dataGridView1.Rows.Count;

它在第一行的同一位置重新显示数据
每次在 datagridview 中找不到代码时添加新行

c# winforms
1个回答
0
投票

在您的情况下,您必须将使用 count (dataGridView1.Rows.Count) 获得的索引减 1。

数组索引从0开始。

© www.soinside.com 2019 - 2024. All rights reserved.