将SELECT查询的结果放入WPF数据网格中

时间:2011-12-06 20:22:20

标签: c# sql wpf

想法是添加窗口,用户可以在其中找到数据库中的任何学生。但是我的错误 列名称错误。 我的方法'代码

string connStr = @"Data Source=.\SQLEXPRESS;
                        AttachDBFileName=C:\Users\Чак\Desktop\ботанизм\ООП\coursework.start\CourseWorkFinal\CourseWorkFinal\University11.mdf;
                        Integrated Security=True";
        SqlConnection conn = new SqlConnection(connStr);
        conn.Open();
        //idstudent={0} AND Name={1} AND Surname={2} AND Middlename={3} AND House={4} AND Street={5} AND Telephone={6}
        string BETA = string.Format("SELECT * FROM Students WHERE Name={0}", "Bob");//textbox1.Text 
        SqlDataAdapter a = new SqlDataAdapter(BETA, conn);
        DataTable x = new DataTable();
        a.Fill(x);//<-there is an exception
        this.dataGrid1.DataContext = x;
        conn.Close();

XAML代码

         <DataGrid AutoGenerateColumns="False" Height="227" HorizontalAlignment="Left" Margin="198,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="443" ItemsSource="{Binding}"/> 

我在数据库中有这样的名字。为什么我有这样的例外?

1 个答案:

答案 0 :(得分:2)

问题在于这行代码:

string BETA = string.Format("SELECT * FROM Students WHERE Name={0}", "Bob");//textbox1.Text 

这需要更改为:

string BETA = string.Format("SELECT * FROM Students WHERE Name='{0}'", "Bob");//textbox1.Text