Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server connection in WPF

Tags:

c#

sql-server

I have a data base in SQL Server 2008 and connecting it in WPF application.I want to read data from table and show in datagrid. Connection is successfully created but when I show it in grid,it show db error(Exception handling). This is what I am doing.Thanks in advance.

  try
  {
       SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
       thisConnection.Open();

       string Get_Data = "SELECT * FROM emp";     

       SqlCommand cmd = new SqlCommand(Get_Data);              
       SqlDataAdapter sda = new SqlDataAdapter(cmd);               
       DataTable dt = new DataTable("emp");
       sda.Fill(dt);
       MessageBox.Show("connected");
       //dataGrid1.ItemsSource = dt.DefaultView;           
  }
  catch
  {
       MessageBox.Show("db error");
  }

It shows connected when i comment the line sda.Fill(dt);

like image 214
EHS Avatar asked Jun 18 '13 11:06

EHS


1 Answers

Your SqlCommand doesn't know you opened the connection- it requires an instance of SqlConnection.

try
{
       SqlConnection thisConnection = new SqlConnection(@"Server=(local);Database=Sample_db;Trusted_Connection=Yes;");
       thisConnection.Open();

       string Get_Data = "SELECT * FROM emp";     

       SqlCommand cmd = thisConnection.CreateCommand();
       cmd.CommandText = Get_Data;

       SqlDataAdapter sda = new SqlDataAdapter(cmd);               
       DataTable dt = new DataTable("emp");
       sda.Fill(dt);

       dataGrid1.ItemsSource = dt.DefaultView;           
}
catch
{
       MessageBox.Show("db error");
}
like image 125
Novak Avatar answered Nov 14 '22 23:11

Novak