user4374239
user4374239

Reputation: 121

How to concatenate Datagridview rows values and store it into one datatable Cell

I have a datagridview with one column, i want to concatenate the datagridview rows values and

insert them in one datable cell. This is code i tried

private string  concatArticle()
    {
        string libArt = null;

        foreach(DataGridViewRow row1 in ListeArt.Rows)
        {
            if (row1 != null)
            {
                libArt = string.Join(",", row1.Cells.Cast<DataGridViewCell>().Select(c => c.Value.ToString()).ToArray());
            }
        }
        return libArt;
    }

and this is the code of inserting values:

SqlCommand CmdService = new SqlCommand("INSERT INTO BonCommande (NumeroBon, LibArticle, Quantite, DateBon)" +
                    "VALUES (@NumeroBon, @LibArticle, @Quantite, @DateBon)", con4);

                CmdService.Parameters.AddWithValue("@NumeroBon", numeroBonTextBox.Text);
                CmdService.Parameters.AddWithValue("@LibArticle", concatArticle());
                CmdService.Parameters.AddWithValue("@Quantite",  Convert.ToInt32(quantiteTextBox.Text));
                CmdService.Parameters.AddWithValue("@DateBon", Convert.ToDateTime(dateBonDateTimePicker.Text));

                CmdService.ExecuteNonQuery();

But when i execute this code i got this error message

NullReferenceException: Object reference not set to an instance of an object.

Where is the error??

Thanks in advance.

Upvotes: 2

Views: 3093

Answers (3)

user4340666
user4340666

Reputation: 1473

Try this:

libArt +=  string.Join(",", row1.Cells.Cast<DataGridViewCell>().Where(c => c.Value != null).Select(c => c.Value.ToString()).ToArray());

Upvotes: 1

Sievajet
Sievajet

Reputation: 3533

The value in your cell is null

Do a null check first:

string.Join(",", row1.Cells.Cast<DataGridViewCell>().Where( c => c.Value != null ).Select( c => c.Value.ToString()).ToArray());

Upvotes: 1

Microsoft DN
Microsoft DN

Reputation: 10030

Try this-

private string  concatArticle()
{
    string libArt = string.Join(", ", ListeArt.Rows.OfType<DataGridViewRow>()
                   .Select(i => i.Cells["yourColumnName"].Value.ToString()).ToArray());
    return libArt;
}

Upvotes: 0

Related Questions