DataGridView Changing DataSource Dynamically
30,644
Solution 1
I had the same problem, after searched and tested a while, finally found the solution:
DataTable dt = new DataTable();
dt.Columns.Add("Column One");
dt.Rows.Add(new object[] { "Item1" });
dt.Rows.Add(new object[] { "Item2" });
dt.Rows.Add(new object[] { "Item3.3" });
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.Columns.Clear();
//dataGridView1.DataSource = null;
dataGridView1.DataSource = dt;
AutoGenerateColumns
needs be true
, that's it.
Solution 2
Instead if doing
DataSource = null
its better to refresh the currency manager, given IQueryable returns CurrencyManager:
(dgvMyPatients.BindingContext[dataGridView1.DataSource] as CurrencyManager).Refresh();
Author by
user962206
Updated on July 09, 2022Comments
-
user962206 almost 2 years
Basically when I create this DataGridView I have this code to fill it up
public void fillDataGrid(IQueryable<PatientInfo> patients) { dgvMyPatients.DataSource = patients; dgvMyPatients.Columns["Pat_Last_Name"].DisplayIndex = 0; dgvMyPatients.Columns["Pat_First_Name"].DisplayIndex = 1; dgvMyPatients.Columns["Pat_Middle_Name"].DisplayIndex = 2; dgvMyPatients.Columns["Pat_First_Name"].HeaderText = "First Name"; dgvMyPatients.Columns["Pat_Last_Name"].HeaderText = "Last Name"; dgvMyPatients.Columns["Pat_Middle_Name"].HeaderText = "Middle Name"; } public IQueryable<PatientInfo> showMyPatients() { DbClassesDataContext myDb = new DbClassesDataContext(dbPath); var patientInfo = from patients in myDb.PatientInfos where patients.Phy_ID == physcianID select patients; return patientInfo; }
So when I create my Object I just do this
fillDataGrid(showMyPatients());
But When I click a button I want to change its contents to something like in this query
private IQueryable<PatientInfo> searchPatient() { DbClassesDataContext myDb = new DbClassesDataContext(dbPath); var search = from myPatients in myDb.PatientInfos where (myPatients.Pat_ID == patient_ID && myPatients.Pat_First_Name.Contains(txtSearch.Text)) || (myPatients.Pat_ID == patient_ID && myPatients.Pat_Last_Name.Contains(txtSearch.Text)) || (myPatients.Pat_ID == patient_ID && myPatients.Pat_Middle_Name.Contains(txtSearch.Text)) select myPatients; return search; }
Then when I click my button It will do this, but it is not updating the datagrid why is that? fillDataGrid(searchPatient());