簡體   English   中英

DataGrid DataBindings Winforms

[英]DataGrid DataBindings Winforms

DataGrid DataBindings錯誤

class Test1
{
   public DataTable table1 = new DataTable();
   public BindingSource sr = new BindingSource();
}

class Test2
{

    Test1 ta =new Test1();

    DataTable table1 = new DataTable();
    table1.Columns.Add("Dosage", typeof(int));
    table1.Columns.Add("Drug", typeof(string));
    table1.Columns.Add("Patient", typeof(string));
    table1.Columns.Add("Date", typeof(DateTime));

    table1.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table1.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table1.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table1.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table1.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

    ta.table1 = table1 ;

   datagridview dgv = new datagridview();
   dgv.AutoGenerateColumns = true ;
   dgv.DataBindings.Add("DataSource",ta,"table1");
}

上面的代碼給我“無法綁定到DataSource.Parameter名稱:dataMember的屬性或列table1”。 我在這里犯了什么錯誤,我沒有理解。有人可以幫助我嗎?

或者,您始終可以創建一個對象列表並綁定該列表。 使用您發布的參數(劑量,DrugName,PatientName和Time)創建“ Patient”類。 然后創建對象並將它們添加到列表中,最后將DGV數據源設置為與該列表相等。 以下是一些可以幫助您的示例代碼:

DataGridView dgvPatient = new DataGridView();      //Create DGV
List<Patient> patientList = new List<Patient>();   //Create list
//Create and populate your object patient
Patient p1 = new Patient(###, "DrugName", "PatientName", DateTime);
patientList.Add(p1);                              //Add to list

dgvPatient.DataSource = typeof(Patient);
dgvPatient.DataSource = patientList;              //Assign to DGV

這是執行此操作的另一種方法,但過去對我來說效果很好。 希望這可以幫助

直接使用DataSource屬性來綁定您的數據源,例如

dgv.AutoGenerateColumns = false;
dgv.DataSource = ta.table1;

根據您發布的代碼,您傳遞的對象數據源是錯誤的,它必須是ta.table1而不是ta

   dgv.DataBindings.Clear();
   dgv.AutoGenerateColumns = false;
   dgv.DataBindings.Add("DataSource",ta.table1,"DataSource");

還將以下行更改為

DataTable table1 = new DataTable("table1");

有關更多信息,請參見MSDN文檔https://msdn.microsoft.com/zh-cn/library/b6y3aby2(v=vs.110).aspx#Examples

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM