从数据库读取数据,并显示在DataGridView中,大概分为三步:
1.首先要建立与数据库的连接;
2.获取到sql server中目标数据库的所有表名,显示在ComboBox中;
3.将数据库中取到的不同表数据通过一定方法,显示在dataGridView中。
具体实现的所有代码已列出来:
public partial class Form0910test : Form
{
public string SqlString;
SqlConnection conn = new SqlConnection();
public Form0910test()
{
InitializeComponent();
}
private void btnlistTable_Click(object sender, EventArgs e)
{
String connectionString = String.Format("server={0};database={1};uid=
{2};pwd={3}", textBoxHost.Text, textBoxDBName.Text, textBoxUser.Text,
textBoxPassword.Text);
SqlConnection sqlconn = new SqlConnection(connectionString);
try
{
sqlconn.Open();
}
catch (Exception ex)
{
MessageBox.Show("数据库连接失败,请检查数据库参数");
return;
}
//声明一个SQLcommand对象
SqlCommand sqlcmd = new SqlCommand("SELECT Name FROM SysObjects Where
XType='U' ORDER BY Name", sqlconn);
//用DataAdapter声明一个对象
SqlDataAdapter sda = new SqlDataAdapter();
//执行查询语句
sda.SelectCommand = sqlcmd;
//创建一个数据集对象
DataSet ds = new DataSet();
//调用DataAdapter对象的Fill()方法来填充数据集
sda.Fill(ds, "Name");
//绑定combobox的数据集
comboDataTable.DataSource = ds.Tables["Name"];
//选定combobox显示的成员及将Name这一列显示在combobox中
comboDataTable.DisplayMember = "Name";
}
private void btnQuery_Click(object sender, EventArgs e)
{
//连接数据库
String connectionStr = String.Format("server={0};database={1};uid=
{2};pwd={3}", textBoxHost.Text, textBoxDBName.Text, textBoxUser.Text,
textBoxPassword.Text);
conn.ConnectionString = connectionStr;
//查询条件
SqlString = "select * from " + this.comboDataTable.Text;
//加载数据并显示
try
{
//查询条件和SqlConnection连接
SqlCommand cmd = new SqlCommand(SqlString, conn);
//数据适配器
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
//DataTable存储数据
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
catch
{ }
finally
{
conn.Close();
}
}
}
}
实现的效果如下图,点击“连接数据库”按钮,连接数据库并可以显示所有数据表;点击“查询”按钮,可以查询并显示某个表的所有数据。