假设有数据库test,里面有一个表student(字段:s_number,s_name,s_sex等)
在Windows Form中的文本框(nameTextBox)中输入姓名,然后按“查询”按钮(searchButton)查询,在DataGrid控件中显示相应的学生信息。
如何实现?请给出源代码!!各位大虾帮忙看看啊!!!!

解决方案 »

  1.   

    如果你的数据库是本地的SQL Server,先导入命名空间:
    using System.Data.SqlClient;
    在查询按钮的click事件中添加如下代码:
    private void searchbutton_Click(....){
        DataSet myds=new DataSet();
        SqlConnection myconn=new SqlConnection("Server=(local);trusted_connection=yes;database=test");
        SqlCommand mycmd=myconn.CreateCommand();
        SqlDataAdapter mypter=new SqlDataAdapter();
        mypter.SelectCommand=mycmd;
        mycmd.CommandText="select * from student where s_name='"+this.nameTextBox.Text.Trim()+"'";
        myconn.Open();
        mypter.File(myds,"student");
        myconn.Close();
        this.dataGrid1.DataSource=myds;
        this.dataGrid1.DataMember="student";
    }
      

  2.   

    在按钮里面添加SqlCommand然后执行就行了啊
      

  3.   

    mypter.Fill(myds,"student");
    调试时这句为什么还报错呢??
      

  4.   

    报错的话是SQL语句的错误,可能与你数据库中的表或者字段名不符,你可以通过捕获异常来看看错误类型,修改代码:try{
    mypter.Fill(myds,"student");
    }
    catch(Exception ex){
    MessageBox.Show(ex.Message);
    }