WPF中的SQL Server连接

EHS*_*EHS 2 c# sql-server

我在SQL Server 2008中有一个数据库并在WPF应用程序中连接它.我想从表中读取数据并显示在中datagrid.连接已成功创建,但当我在网格中显示它时,它显示db错误(异常处理).这就是我在做的事.谢谢.

  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");
  }
Run Code Online (Sandbox Code Playgroud)

它显示connected我评论该行的时间 sda.Fill(dt);

Nov*_*vak 7

SqlCommand不知道你打开了连接 - 它需要一个实例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");
}
Run Code Online (Sandbox Code Playgroud)