datagridview 查询数据库数据
private void btnsearch_Click(object sender, EventArgs e) { if (txtSearch.Text != "") { this.dataGridView1.DataSource = null; string str = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; SqlConnection sqlConnection = new SqlConnection(str); sqlConnection.Open(); string sql = String.Format("select * from Student where Name='{0}'", txtSearch.Text); SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, sqlConnection); DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); this.dataGridView1.DataSource = dataSet.Tables[0].DefaultView; sqlConnection.Close(); } else { load(); } }