2017-07-26 42 views
0

DataGrid的數據綁定錯誤DataGrid的數據綁定的WinForms

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名稱的屬性或列表1:數據成員。」 。我在這裏犯了什麼錯誤,我沒有得到它。可以幫我嗎?

+0

__不要調用一個'DataGridView''GridView'或'DataGrid',反之亦然!這是錯誤的和混亂的,因爲這些是不同的控制。總是用__right__的名字打電話給他們! – TaW

回答

0

直接使用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/en-us/library/b6y3aby2(v=vs.110).aspx#Examples

+0

我在使用數據綁定綁定到數據源的情況。你能幫我找到databindings.add()方法的問題。 – Aishwarya

+0

@Aishwarya,請參閱編輯答案如果幫助 – Rahul

+0

更改後如上,我得到相同的錯誤。謝謝你的迴應。 – Aishwarya

0

或者,您始終可以創建對象列表並綁定列表。用您發佈的參數(劑量,藥物名稱,患者名稱和時間)創建一個「患者」類。然後創建對象並將它們添加到列表中,最後將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 

這是一種不同的方式去這樣做,但一直工作得很好,我過去。希望這可以幫助

+0

嗨Yahtzee謝謝你的回覆。根據你的建議,上述建議對我有用。但我需要使用DataBindings.Add方法綁定DataGridView的數據源屬性,這不適用於我。我不知道爲什麼它不起作用,我需要幫助。 – Aishwarya