gpt4 book ai didi

c# - DataGridView 动态更改数据源

转载 作者:行者123 更新时间:2023-12-02 07:37:05 25 4
gpt4 key购买 nike

基本上,当我创建这个 DataGridView 时,我有这段代码来填充它

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;
}

所以当我创建对象时我就这样做

fillDataGrid(showMyPatients());

但是当我单击按钮时,我想将其内容更改为类似于此查询的内容

 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;
}

然后,当我单击按钮时,它会执行此操作,但它不会更新数据网格,这是为什么? fillDataGrid(searchPatient());

最佳答案

我也遇到了同样的问题,经过一番搜索和测试,终于找到了解决方案:

        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 需要为 true,就是这样。

关于c# - DataGridView 动态更改数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com