c# - 如何获取 DataGridView 行值并将其存储在变量中?

标签 c# datagridview

我如何一次遍历 DataGridView 的行(我有 2 列),然后将这 2 列存储在一个变量中,我将用作 sql 查询的参数?

  foreach (DataGridViewRow Datarow in contentTable_grd.Rows)
            {
                contentValue1 = Datarow.Cells[0].Value.ToString();
                contentValue2 = Datarow.Cells[1].Value.ToString();

                SqlParameter param4 = new SqlParameter("@contentTableValue1", contentValue1);
                SqlParameter param5 = new SqlParameter("@contentTableValue2", contentValue2);

            }

我在使用上面的代码时遇到这个错误-

Object reference not set to an instance of an object.

最佳答案

最可能的问题是您引用的一个或两个单元格包含空值,并且当您尝试在此类单元格上调用 ToString() 时会抛出异常。

一种解决方案是使用 ?? operator如果单元格值为空,则返回参数的默认值:

contentValue1 = Datarow.Cells[0].Value ?? string.Empty;
contentValue2 = Datarow.Cells[1].Value ?? string.Empty;

如果单元格的值为空,此代码将返回一个空字符串;您可能希望使用不同的默认值。

关于c# - 如何获取 DataGridView 行值并将其存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6934477/

相关文章:

c# - BindingSource.Filter 最大长度

winforms - 如何从winforms c#中的datagridview中删除行指示器列

c# - datagridview向上滚动

c# - 从 DataGridView 单元格中删除填充/边距

c# - OWIN 安全性 - 如何在维护身份验证承载 token 的同时返回 cookie 中的刷新 token

c# - 将自定义数据/值传递到事件系统

c# - 将 Firefox 嵌入到 .NET 控件中

c# - 使用列表集合的 find 方法

c# - C# 中的 Java Character.charCount

vb.net - 如何使 DataGridViewComboBoxColumn 的 ComboBox 接受用户新项目?