遍历DataGridView行单元格值时遇DataGridRow无Cells定义错误
问题解决方法
1. 修正行类型错误
你代码里误用了DataGridRow,WinForms中DataGridView的行类型是**DataGridViewRow**,这是触发错误的核心原因,把循环里的行类型替换成DataGridViewRow即可。
2. 修复拼写错误
代码里row.Cells["name"].Valu?.ToString()中的Valu少了一个字母e,应该改为Value。
修正后的完整代码
foreach (DataGridViewRow row in dataGrid_users.Rows) { // Retrieve cell values from the row string name = row.Cells["name"].Value?.ToString(); string surname = row.Cells["surname"].Value?.ToString(); string goal = row.Cells["goal"].Value?.ToString(); string operation = row.Cells["operation"].Value?.ToString(); string description = row.Cells["discription"].Value?.ToString(); string job = row.Cells["job"].Value?.ToString(); string station = row.Cells["station"].Value?.ToString(); string date = row.Cells["date"].Value?.ToString(); }
额外注意事项
- 确保代码文件顶部有
using System.Windows.Forms;指令,且项目已引用System.Windows.Forms程序集。 - 如果
dataGrid_users是WPF的DataGrid而非WinForms的DataGridView,则不能通过Cells访问值,需从绑定的数据源取值,示例如下:foreach (var item in dataGrid_users.Items) { // 假设数据源是自定义实体类User User user = item as User; string name = user?.Name; // 其他字段同理 }
内容的提问来源于stack exchange,提问作者Daryush
相关产品推荐
相关产品推荐

