0

I have an ArrayList , it has a string at 0th position and DataTable at 1st position is it possible to get DataTable back?

ArrayList dataModel = new ArrayList();
DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Columns.Add("B");
dt.Columns.Add("C");
dt.Rows.Add("1","Rahul","Vapi");
dt.Rows.Add("2", "Yash", "Vapi");
dt.Rows.Add("3", "Dinesh", "vapi");

dataModel.Add("this is working for me");
dataModel.Add(dt);

I am getting this error :

Cannot implicitly convert type 'object' to 'System.Data.DataTable'. An explicit conversion exists (are you missing a cast?)

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
yash fale
  • 235
  • 1
  • 4
  • 19
  • That's so wrong...how about using a `List>` – Pikoh Feb 07 '17 at 10:45
  • @Pikoh: sure, you should not need to use an `ArrayList` anymore. But your example doesn't help. OP has only two items, a string and a `DataTable`. So if you want to replace this with a generic collection you need to use a `List` in which case you also need to cast the items. – Tim Schmelter Feb 07 '17 at 10:46
  • @pikoh: because that's how OP uses the arraylist. He doesn't need a way to store multiple string-DataTable combinations which you could handle with a `List>`. There is only one string and one DataTable. Of course he should use two separate variables(local variables, properties or fields) instead or a class that encapsulates both. – Tim Schmelter Feb 07 '17 at 10:50
  • Please try this Datatable to Arraylist http://stackoverflow.com/a/3573771/1849024 – imsome1 Feb 07 '17 at 10:51
  • @TimSchmelter yes, now i see. Anyway, i would use a `Dictionary` and that way you won't need to cast the datatable back. Or,as you say,a class. – Pikoh Feb 07 '17 at 10:52
  • 1
    @pikoh: If you want to support multiple it would be much better to provide a custom class with two properties and then use a `List`. – Tim Schmelter Feb 07 '17 at 10:54
  • @TimSchmelter agreed :) – Pikoh Feb 07 '17 at 10:55

1 Answers1

1

(are you missing a cast?)

Yes.

DataTable dt = (DataTable) dataModel[1];
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939