EHS EHS - 1 month ago 11
C# Question

SQL Server connection in WPF

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);

Answer

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");
}