End Google Ads 201810 - BS.net 01 --> Hi!

There must be a smarter way to do this! This is about if I can bind a simple datastructure to a table.

Problem: I want to hold an instance of a (simple) datastructure - say a List or a Collection or similar - I don't care - representing the contents of a view or table - say view. How to impl. that the most natural/generic way?

My solution:

// Fill DataTable.
DataTable dt = new DataTable();
string strConn = "Data Source=MyPC\\SQLExpress; Initial Catalog=MyDBInst; Integrated Security=True; User ID=; Password=;";
SqlConnection con = new SqlConnection(strConn);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM v_SomeViewOfMine", con);
da.Fill(dt);

// Populate List.
List my_list = new List();
foreach(DataRow dr in dt.Rows)
my_list.Add(new TestClass(
(string)dr.ItemArray[0],
(int)dr.ItemArray[1],
(int)dr.ItemArray[2],
(int)dr.ItemArray[3]));
con.Close();

Where constructor TestClass is:

public TestClass(string s, int a, int b, int c)
{ Name = s; Category = a; Conference = b; SubCategory = c; }

This approch works - "all is fine" and list is fine! Or is it? I feel that I miss some binding michanism-thingy like (pseudo):

List my_list = new List();
my_list.BindToDataTable(dt);
my_list.SetBindingColumn("Name", "Name", Type.string);
my_list.SetBindingColumn("Category", "Category", Type.int);
my_list.SetBindingColumn("Conference", "Conference", Type.int);
my_list.SetBindingColumn("Sub category", "SubCategory", Type.int);

Inspired from how one would setup a DataGrid in a xaml (< DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />).

So in other words: Do I have to iterate the DataTable myself (dealing with dr.ItemArray[] typed object) or can I bind it to a datastructure in some way?

Thank's in advance.
Michael Mogensen
modified on Saturday, October 30, 2010 8:56 PM