Thursday, February 17, 2011

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?

From stackoverflow
  • 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");
    
    DataRow dr = dt.NewRow();
    dr["column1"] = "value1";
    dt.Rows.AddNew(dr);
    
    myDataGrid.DataSource = dt;
    myDataGrid.DataBind();
    
  • 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);
    
  • how i insert data to next row in datagrid . i while loop it inserts to same row which causes exception.

0 comments:

Post a Comment