回 帖 发 新 帖 刷新版面

主题:如何把数据库查询出来的数据放进datagridview中

如何把数据库查询出来的数据放进datagridview中,要详细代码!在线等

回复列表 (共2个回复)

沙发

private void btnSelcet_Click(object sender, EventArgs e)
        {
            string strSelect = this.txtSelect.Text.Trim();
            string StrGuanjzi = this.txtGuanjz.Text.Trim();
            string cmd= "";
            if ((txtSelect.Text == "") || (txtGuanjz.Text == ""))
            {
                MessageBox.Show("查询,关键字不能为空!", "提示!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                switch (strSelect)
                {
                    case "序号":

                         cmd = "Select * from PensonlInformation Where id='" + StrGuanjzi + "'";
                        break;
                    case "姓名":
                         cmd = "Select * from PensonlInformation Where name='" + StrGuanjzi + "'";
                        break;
                    case "性别":
                         cmd = "Select * from PensonlInformation Where sex='" + StrGuanjzi + "'";
                        break;
}
                string conString = ConfigurationSettings.AppSettings["ConnectionString"]; //"server =(local) ;database=data_base;User Id = sa;pwd=123456"
                SqlConnection con = new SqlConnection(conString);
                try
                {
                    con.Open();
                    SqlDataAdapter AdapterSelect = new SqlDataAdapter(cmd, con);
                    //创建DataTable对象实例
                    DataTable dt = new DataTable();
                    AdapterSelect.Fill(dt);
                    //填冲控件
                    dataGridView1.DataSource = dt.DefaultView; 
                }
                finally
                {
                 con.Close();

                }

                
            }
        }

板凳

先把查询出来的数据放到一个DataTable中,然后将DataGridView的数据源设置成DataTable即可。
SqlConnection conn=new SqlConnection();//省略,连接数据库
SqlCommand cmd=new SqlCommand(查询语句,conn);
SqlDataAdapter sda=new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
dt.Clear();
sda.Fill(dt);
dataGridView1.DataSource=dt;

我来回复

您尚未登录,请登录后再回复。点此登录或注册