How to auto-update DataGridViewColumn?

65 views Asked by At

I created a DataGridView and generate one of the columns by following code:

DataTable accessDT = SQL.GetDT(@"select * from [Access]");  //Custom-made method to get the DataTable.

DataGridViewComboBoxColumn dcAccess = new DataGridViewComboBoxColumn();
dcAccess.Name = "Access";
dcAccess.HeaderText = "權限";
dcAccess.DataSource = accessDT;
dcAccess.ValueMember = "ID";
dcAccess.DisplayMember = "Name";
dgvUser.Columns.Add(dcAccess);

It will populate the "Access" column with dtAccess, that's no problem at all.

But I don't know how to let it update automatically upon any change of the table [Access].

I tried to get the DataTable again and do Update() and Refresh(), but the "Access" column is still the old data.

And I can't find any DataSource under dgvUser.Columns["Access"] once it was created.

Could somebody please be so kind and teach me how to let it auto-update properly?

Much appreciated!

1

There are 1 answers

0
Caius Jard On BEST ANSWER

I imagine your GetDT method looks something like this:

public DataTable GetDT(string sql){
  var dt = new DataTable();
  using(x as new OleDbDataAdapter(sql, connectionstring))
    x.Fill(dt);
  return dt;
}

If it doesn't, it should - dataadapters know how to create and open connections etc, so these 4 lines are really all you need to create a datatable, fill and return it.

Anyway.. Modify or add another method like:

public void FillDT(string sql, DataTable dt){
  dt.Clear();
  using(x as new OleDbDataAdapter(sql, connectionstring))
    x.Fill(dt);
}

Then use it to periodically refill your dt that is the datasource for the column:

var dt = (dgvUser.Columns["Access"] as DataGridViewComboBoxColumn).DataSource as DataTable;

FillDT("SELECT...", dt);