技术问询:如何在DataGridView中添加行?填充首行[0]后如何添加新行?
解决DataGridView添加新行及填充后新增行的问题
首先咱们先理清你现有代码的问题:DTG.Rows.Clear()会清空所有行,之后直接访问DTG.Rows[0]会触发索引越界异常,而且循环里只是重复覆盖第一行的值,根本没实现创建新行的逻辑。下面分两种场景给你针对性的解决方法:
1. 批量添加多行到DataGridView
如果要像你代码里那样循环生成10行,每次循环都先创建新行再赋值就可以了:
public void preencherDTG() { DTG.Rows.Clear(); // 先清空现有行 for (int i = 0; i < 10; i++) { // 1. 添加新行,获取刚创建的行的索引 int newRowIndex = DTG.Rows.Add(); DataGridViewRow newRow = DTG.Rows[newRowIndex]; // 2. 给新行的单元格赋值 newRow.Cells[0].Value = cbModelo.Text; newRow.Cells[1].Value = txtPlaca.Text; newRow.Cells[2].Value = txtTotal.Text; } }
嫌麻烦的话还可以用更简洁的写法,直接把单元格值作为参数传入Add方法,自动完成新行创建和赋值:
public void preencherDTG() { DTG.Rows.Clear(); for (int i = 0; i < 10; i++) { // 直接传值,一步创建新行并赋值 DTG.Rows.Add(cbModelo.Text, txtPlaca.Text, txtTotal.Text); } }
2. 填充首行后,再添加另一行
如果是先填充好第一行,之后再手动新增其他行,可以拆成两个方法来实现:
// 先填充首行 public void PreencherPrimeiraLinha() { DTG.Rows.Clear(); // 添加首行并赋值 int firstRowIndex = DTG.Rows.Add(); DataGridViewRow firstRow = DTG.Rows[firstRowIndex]; firstRow.Cells[0].Value = cbModelo.Text; firstRow.Cells[1].Value = txtPlaca.Text; firstRow.Cells[2].Value = txtTotal.Text; } // 后续调用此方法添加新行 public void AdicionarNovaLinha() { // 创建新行并赋值(这里可以给新行设置不同的值,或者和首行一致) int newRowIndex = DTG.Rows.Add(); DataGridViewRow newRow = DTG.Rows[newRowIndex]; newRow.Cells[0].Value = cbModelo.Text; newRow.Cells[1].Value = txtPlaca.Text; newRow.Cells[2].Value = txtTotal.Text; }
关键注意点:
- 永远不要直接访问
Rows[0],除非你能确定DataGridView里已经存在该行,否则会抛出IndexOutOfRangeException。 Rows.Add()是最安全的添加新行方式,它会自动在DataGridView中创建新行,并返回该行的索引,方便后续操作。- 如果需要给新行设置特殊样式、只读属性等,可以先获取返回的
DataGridViewRow对象再做调整。
内容的提问来源于stack exchange,提问作者Pvxtotal
相关产品推荐
相关产品推荐

