-2

I am trying to load back values from a CSV to my class. Then display the values to my datatable. However, I get the error even after my values have been loaded into the class and placed inside the intended columns (See Figure 1). The error occurred at dt.Rows.Add(dr);. Below is my code:

 public Newdatagrid()
    {
        InitializeComponent();

        //Do datatable
        ds = new DataSet();
        dt = new DataTable();
        dt.Columns.Add("Bus Model", typeof(string));//0
        dt.Columns.Add("Bus Type", typeof(string));//1
        dt.Columns.Add("Mileage", typeof(string));//2

        if (Savestate.vehnochange_list.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                dr["Bus Model"] = Savestate.busmodel_list[Savestate.busmodel_list.Count];//0
                dr["Bus Type"] = Savestate.bustype_list[Savestate.bustype_list.Count];//1
                dr["Mileage"] = Savestate.busmileage_list[Savestate.busmileage_list.Count];//2
            }

            dt.Rows.Add(dr);
            this.dataGridView2.DataSource = dt;

        }
   }
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
masyita shariff
  • 110
  • 1
  • 8
  • 1
    Why would you want to store `Mileage` as string? If you have what looks like 3 lists or arrays, rather than a datatable, a List made up up the contents of all three might be more appropriate – Ňɏssa Pøngjǣrdenlarp Jul 31 '19 at 01:34
  • `dt.Rows.Add(dr);` **That** `dr` is a different one to the one in your loop. `dt.Rows.Add(dr);` should be **inside** the `foreach`. – mjwills Jul 31 '19 at 02:06

1 Answers1

0

I think you want something like this:

public Newdatagrid()
{
    InitializeComponent();

    //Do datatable
    ds = new DataSet();
    dt = new DataTable();
    dt.Columns.Add("Bus Model", typeof(string));//0
    dt.Columns.Add("Bus Type", typeof(string));//1
    dt.Columns.Add("Mileage", typeof(string));//2

    if (Savestate.vehnochange_list.Count > 0)
    {
        for (int i=0; i < Savestate.vehnochange_list.Count; ++i)
        {
            DataRow dr = dt.NewRow();
            dr["Bus Model"] = Savestate.busmodel_list[i];//0
            dr["Bus Type"] = Savestate.bustype_list[i];//1
            dr["Mileage"] = Savestate.busmileage_list[i];//2
            dt.Rows.Add(dr);
        }

        this.dataGridView2.DataSource = dt;

    }
}
MPost
  • 535
  • 2
  • 7