KMC
KMC

Reputation: 20046

DataGrid show an empty row when DataTable is empty

I have a DataGrid (dg1) that binds to a DataTable (DataSet.Tables). The code runs fine and DataGrid is showing the Data in DataTable correctly.

But, if I Clear() the DataTable, the DataGrid is also clear but left with one single empty row, which I don't know how to get rid of. I have already cleared the DataTable. Where is this empty row come from?

SqlCeDataAdapter da = new SqlCeDataAdapter();

string sqlStr = @"SELECT * FROM FooTable";
da.SelectCommand = new SqlCeCommand(sqlStr, conn);

da.Fill(ds, "FooTable");

/* get data table reference */
dt = ds.Tables["FooTable"];

DataRow newRow = dt.NewRow();
newRow["FooName"] = "Donkey";
dt.Rows.Add(newRow);

dg1.ItemsSource = ds.Tables[0].DefaultView;
dt.Clear();

enter image description here

Upvotes: 2

Views: 4201

Answers (3)

Kishore Borra
Kishore Borra

Reputation: 269

@Abdul Muqtadir : Correct explanation.

The below code will do what you are looking for:

   dataGridView1.AllowUserToAddRows = false;
   dataGridView1.DataSource = null;

for Datagrid you should set DataGrid.CanUserAddRows to false;

Upvotes: 0

brunnerh
brunnerh

Reputation: 185578

That row normally is the NewItemPlaceholder which is used to create new items in the bound collection. You should try setting CanUserAddRows to false.

Upvotes: 6

FIre Panda
FIre Panda

Reputation: 6637

The empty row that is shown is probably due to the reason that by default in datagrid, empty row is there in the last so that the user can add new row. try doing dataGridView1.AllowUserToAddRows = false;

Upvotes: 1

Related Questions