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.
CodePudding user response:
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();
CodePudding user response:
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();
}
}
}