简体   繁体   中英

DataGrid DataBindings Winforms

DataGrid DataBindings Error

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

the above code giving me "Cannot bind to the property or column table1 on the DataSource.Parameter name: dataMember." . What mistake i ma doing here ,i did not get it .Can any one help me ?

Alternatively, you could always create an object list and bind the list. Create a "Patient" class with the parameters you posted (Dosage, DrugName, PatientName, and Time). Then create objects and add them to a list and finally set the DGV datasource equal to that list. Here's some sample code that could help you:

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

This is a different way to go about doing it but has worked pretty well for me in the past. Hope this helps

Use the DataSource property directly to bind your data source like

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

Well per your posted code the object data source you are passing is wrong, it has to be ta.table1 instead of just ta

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

Also change the below line as

DataTable table1 = new DataTable("table1");

See MSDN documentation https://msdn.microsoft.com/en-us/library/b6y3aby2(v=vs.110).aspx#Examples for more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM