jukus
jukus

Reputation:

Can you add data to a datagrid with no data source?

I have a DataGrid with 5 template columns,

However when I try and add some dynamically created controls into the grid, it fails, as there are no rows.

-Can i add a blank row in and use that? and how? -Or any other way?

Upvotes: 4

Views: 21598

Answers (2)

Kon
Kon

Reputation: 27441

I'm pretty sure you have to bind to a data source. But it's easy enough to create your own DataTable and insert a row into it with some dummy info.

//pseudo code:

DataTable dt = new DataTable();
DataColumn dc = new DataColumn("column1");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr["column1"] = "value1";
dt.Rows.AddNew(dr);

myDataGrid.DataSource = dt;
myDataGrid.DataBind();

Upvotes: 7

Chris Miller
Chris Miller

Reputation: 4899

If you are using an unbound DataGridView, you can create new rows and then add them to DataGridView. Your question referred to DataGrid, but you tagged it for DataGridView.

// Sample code to add a new row to an unbound DataGridView
DataGridViewRow YourNewRow = new DataGridViewRow();

YourNewRow.CreateCells(YourDataGridView);
YourNewRow.Cells[0].Value = "Some value";
YourNewRow.Cells[1].Value = "Another value";

YourDataGridView.Rows.Add(YourNewRow);

Upvotes: 7

Related Questions