简体   繁体   中英

C# Datagridview to array

I have a project where I'm doing a datagridview for a shopping cart. I figured the best way to do it would be to add datagridview cells to an array.

My question is how to you add a datagridview cell or row to an array? I have been stumped by this. Please help.

Here is a language extension to create a string array for a DataGridView.

public static class DataGridViewExtensions
{
    public static string[] ToArray(this DataGridView sender, string defaultNullValue = "(empty)")
    {
        return (sender.Rows.Cast<DataGridViewRow>()
            .Where(row => !row.IsNewRow)
            .Select(row => new
            {
                row,
                rowItem = string.Join(",", Array.ConvertAll(row.Cells.Cast<DataGridViewCell>()
                    .ToArray(), c => ((c.Value == null) ? defaultNullValue : c.Value.ToString())))
            })
            .Select(@row => @row.rowItem)).ToArray();

    }

}

Usage

var results = yourDataGridView.ToArray();
    private void btnConvert_Click(object sender, EventArgs e)
{
    //Creating DataTable.
    DataTable dt = new DataTable();
 
    //Adding the Columns.
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        dt.Columns.Add(column.HeaderText, column.ValueType);
    }
 
    //Adding the Rows.
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        dt.Rows.Add();
        foreach (DataGridViewCell cell in row.Cells)
        {
            dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM