I have a WPF application connected to SQL Server; while I load up to 10 records into my DataGrid
, my application works fine and response is too fast, but when I load all rows (which is almost 1000), my application took around 15 seconds to load and freezes the entire UI.
But when I execute the same query in SQL Server, it only took around 00:00:00.490 seconds to load those 1000 rows which is too fast. What I already have done is as below to avoid UI freezing and query execution fast. What I am doing wrong? Please guide with code snippets as I am new to C# world.
// Calling function to load data into DataGrid in a new thread,
// to make UI responsive.
String qry = "select * from institutes_tbl"
DataGrid dg = MainDataGrid;
Thread thread = new Thread(() => FunDataGrid_DataView(dg, qry));
thread.IsBackground = true;
thread.Start();
But unfortunately my UI shows message "Not Responding". Below is the function definition:
public void FunDataGrid_DataView(DataGrid dg, string qry)
{
Application.Current.Dispatcher.BeginInvoke
(
DispatcherPriority.Background,
new Action(() =>
{
try
{
con = new SqlConnection(con_string);
cmd = new SqlCommand(qry, con);
cmd.CommandTimeout = 12 * 3600;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dg.ItemsSource = dt.DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!",
MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
));
}
Here is my XAML:
<DataGrid x:Name="DataGrid_View"
MouseLeftButtonUp="DataGrid_View_MouseLeftButtonUp"
ItemsSource="{Binding DATA_TBL}"
LoadingRow="DataGrid_View_LoadingRow" Grid.Row="2"
Grid.Column="0" ScrollViewer.CanContentScroll="False"
AutoGenerateColumns="False" CanUserAddRows="False"
Background="#7F179DB2" CellStyle="{StaticResource CellStyle}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding NAME}" Width="5*"/>
<DataGridTextColumn Header="Father Name"
Binding="{Binding F_NAME}" Width="5*"/>
<DataGridTextColumn Header="CNIC"
Binding="{Binding CNIC}" Width="5*"/>
</DataGrid.Columns>
</DataGrid>
I want my UI to be responsive and data to load fast. I am working on local host right now.