开发者

How can I get DataGridView row values and store them in variables?

How can I loop through the rows of a DataGridView one at a time (I have 2 columns), then store those 2 columns in a variable that will be used as a parameter for an sql query?

foreach (DataGridViewRow Datarow in contentTable_grd.Rows)
{
    cont开发者_开发百科entValue1 = Datarow.Cells[0].Value.ToString();
    contentValue2 = Datarow.Cells[1].Value.ToString();
    
    SqlParameter param4 = new SqlParameter("@contentTableValue1", contentValue1);
    SqlParameter param5 = new SqlParameter("@contentTableValue2", contentValue2);
}

I'm getting this error when using the above code:

Object reference not set to an instance of an object.


The most likely problem is that the one or both the Cell's you're referencing contains a null value and the exception is thrown when you attempt to call ToString() on such a cell.

One solution is to use the ?? operator to return a default value for your parameter if a Cell Value is null:

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

This code will return an empty string if a cell's Value is null; you might wish to use a different default.


Found the problem I needed an if statement to prevent empty cells from going through

    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);
        }

    }


what is contentValue1?

Not sure about c# -- can it implicitly type the variable? Maybe try something like string contentvalue1 = ...

Also, depending on what kind of control might be in the cell...you might do something like

string contentvalue1 = CTYPE(DataRow.FindControl("myTextbox"),textbox).text

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜