如何获取DataGridView行值并存储在变量中?

kur*_*_89 5 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);

            }
Run Code Online (Sandbox Code Playgroud)

使用上面的代码时出现此错误 -

你调用的对象是空的.

Jay*_*ggs 5

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

一种解决方案是使用?? 如果Cell Value为null,则运算符返回参数的默认值:

contentValue1 = Datarow.Cells[0].Value ?? string.Empty;
contentValue2 = Datarow.Cells[1].Value ?? string.Empty;
Run Code Online (Sandbox Code Playgroud)

如果单元格的Value为null,则此代码将返回空字符串; 您可能希望使用其他默认值.


kur*_*_89 4

发现问题我需要一个 if 语句来防止空单元格通过

    foreach (DataGridViewRow Datarow in contentTable_grd.Rows)
    {
        if (Datarow.Cells[0].Value != null && Datarow.Cells[1].Value != null)
        {
            contentValue1 = Datarow.Cells[0].Value.ToString();
            contentValue2 = Datarow.Cells[1].Value.ToString();
            MessageBox.Show(contentValue1);
            MessageBox.Show(contentValue2);
        }

    }
Run Code Online (Sandbox Code Playgroud)