Tuesday, 11 June 2013

DataTable Column to List in c#

Using LINQ:

table.AsEnumerable().Select(s => s["ID"].ToString()).ToList();

Wednesday, 3 April 2013

Find controls in WPF

Consider this data grid in wpf

<DataGrid Name="dataGrid1">
   <DataGridTemplateColumn >

               <StackPanel Name= "sp" >
                <TextBlock  Name="textBlock1" />                                                           </StackPanel>

 <DataGridTemplateColumn >

To access element  "textBlock1" which is inside stackpanel, we can use the following code.

foreach (StackPanel sp in FindVisualChildren<StackPanel>(dataGrid1))
                        if (sp.Name == "sp")
                            TextBlock txt= (TextBlock)sp.FindName("textBlock1");       
  public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
            if (depObj != null)
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                        yield return (T)child;

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                        yield return childOfChild;

Tuesday, 5 February 2013

sql bulkcopy

sql bulk copy from datatable into sql table(with transaction)

 Dim con As New  SqlConnection("connection string")

 Dim myTransaction As SqlTransaction = con.BeginTransaction()
 Dim bulkCopy As New SqlBulkCopy(con, SqlBulkCopyOptions.Default,   myTransaction)

bulkCopy.DestinationTableName = "table name"

you can use column mapping
bulkCopy.ColumnMappings.Add("column name in datatable", "column name in sql table")

LINQ query to DataTable

Converting Anonymous type generated by LINQ to a DataTable type(here LINQ left outer join)

  customer                                                      city

id   name  city_id                                     cid       city_name                         

1     xxx        2                                             1           aaa

2     yyy         3                                            2           bbb

                                                                     3           ccc

First create temporary datatable with columns you need

Dim tbTemp As New DataTable

Using left outer join  

 Dim JoinedResult As IEnumerable(Of DataRow) = From t1 In                                                customer.AsEnumerable()
         Group Join t2 In city.AsEnumerable()
         On t1.Field(Of String)("city_id") Equals t2.Field(Of String)("cid")
        Into RightTableResults = Group
        From t In RightTableResults.DefaultIfEmpty
        Select tbTemp.LoadDataRow(New Object() {t1.Item("cust_name"),      t.Item("city_name")})

 Dim tbResult As New DataTable