Tag Archives: dynamic binding

Dynamic ItemsSource in WPF

I was just playing around and I had an idea of binding data dyanmically to a telerik gridview. I have some 25 tables in a database and I give the option to select the table to the user and the gridview should display data from that table.

I used some help from stackoverflow.

  <telerik:RadGridView ItemsSource="{Binding TableData}" AutoGenerateColumns="True"/>

and a extension method for data reader

        public static IEnumerable<dynamic> AsEnumerable(this System.Data.IDataReader source)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            var columns = Enumerable.Range(0, source.FieldCount).Select(source.GetName).ToList();

            while (source.Read())
            {
                
                dynamic dRow = new ExpandoObject();
                foreach (var column in columns)
                {
                    ((IDictionary<string, object>)dRow).Add(column, source[column]);
                }
                yield return dRow;
            }
        }

and bind it to the ObservableCollection. That’s it.