WinForms DataGridView通过Add New Row新增行触发事件咨询
DataGridView添加新行对应的触发事件
当你通过DataGridView底部的“添加新行”行(NewRow)完成新行添加操作时,最匹配需求的事件是UserAddedRow——这个事件会在用户通过UI完成新行添加(比如输入内容后离开该行、按回车确认)时触发,刚好对应你需要检查内容并手动更新数据源的场景。
事件使用示例
- 绑定事件(可在窗体构造函数或设计器中完成):
dataGridView1.UserAddedRow += DataGridView1_UserAddedRow;
- 编写事件处理逻辑:
private void DataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e) { // 获取用户刚添加的新行 DataGridViewRow newRow = e.Row; // 检查单元格内容(示例:校验第一列非空) if (string.IsNullOrWhiteSpace(newRow.Cells[0].Value?.ToString())) { MessageBox.Show("第一列内容不能为空"); dataGridView1.Rows.Remove(newRow); return; } // 手动更新绑定的数据源(假设数据源为DataTable) DataTable dt = (DataTable)dataGridView1.DataSource; DataRow dr = dt.NewRow(); for (int i = 0; i < newRow.Cells.Count; i++) { dr[i] = newRow.Cells[i].Value ?? DBNull.Value; } dt.Rows.Add(dr); }
补充说明
CellBeginEdit仅触发于单元格开始编辑时,此时新行尚未正式添加到数据源,无法满足你的需求CellContentClick仅在点击单元格内容时触发,对直接输入内容的场景不适用UserAddedRow是专门针对用户通过UI添加新行的事件,无需用CellValueChanged做变通处理
内容的提问来源于stack exchange,提问作者FredAndBarney
相关产品推荐
相关产品推荐

