SQL查询结果显示在datagridview

///<summary>

        ///显示查询结果

        ///</summary>

        ///<param name="str">查询关键字</param>

        private void ShowDeptResult(string str)

        {

            string conStr = "Data Source = localhost; Integrated Security = SSPI; Initial Catalog = EKGStudio; User ID = sa; password = ECGecg123"; //数据库连接串

            SqlConnection sqlCont =new SqlConnection(conStr); //创建数据库连接

            if (sqlCont.State == ConnectionState.Open)         //检查连接状态

            {

                sqlCont.Close();

            }

            sqlCont.Open();   //打开数据库连接

            String searchStr = "SELECT NAME, CODE FROM dbo.DICT_DEPT WHERE NAME LIKE '%" + str + "%'";

            //返回查询结果

            DataSet ds = new DataSet(); 

            SqlDataAdapter dataAdpt =new SqlDataAdapter(searchStr, sqlCont);  //执行查询

            dataAdpt.Fill(ds);

            //注:此前要先填充DataGridView的列

            dtGrdVewDept.Rows.Clear();  //清空原有datagridview列表

           

            //将SQL的查询结果显示在datagridview中

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)

            {

                dtGrdVewDept.Rows.Add(i+1,ds.Tables[0].Rows[i][0],ds.Tables[0].Rows[i][1]);

            }

            sqlCont.Close();

 

        }

 

 

或直接:

            //返回查询结果

            DataSet ds = new DataSet();

            SqlDataAdapter dataAdpt = new SqlDataAdapter(searchStr, sqlCont);  //执行查询

            dataAdpt.Fill(ds);

            dataGridView1.DataSource=ds.Tables[0];         


            sqlCont.Close();

 

展开阅读全文

没有更多推荐了,返回首页