具体的实现步骤如下:
1、新建Windows窗体应用程序,添加DataGridView控件,不对DataGridView控件做任何处理(只做拉伸,防止看不到数据)
2、为【查看记录】按钮添加事件:代码如下
1)数据库操作类:
class DBConnection
{
private MySqlConnection connection;
private string connectionStr;
public DBConnection()
{
try
{
connectionStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
connection = new MySqlConnection(connectionStr);
}
catch (Exception exception)
{
throw new Exception("DBConnection Constructor:" + exception.Message);
}
}
public DataSet Select()
{
try
{
if (connection != null)
{
connection.Open();
}
string cmdStr = "Select * from t_family";
MySqlCommand sqlCmd = new MySqlCommand(cmdStr, connection);
MySqlDataAdapter sda = new MySqlDataAdapter(sqlCmd);
DataSet ds = new DataSet();
sda.Fill(ds,"t_family");
return ds;
}
catch (Exception exception)
{
throw new Exception("SelectMethod:"+exception.Message);
}
finally
{
connection.Close();
}
}
}
2)数据显示方法:
private void button1_Click(object sender, EventArgs e)
{
DBConnection conn = new DBConnection();
DataSet dataset = conn.Select();
if (dataset == null)
{
MessageBox.Show("没有数据");
}
dataGridView1.DataSource = dataset.Tables[0];
}
3、显示结果:
4、如果想展示成为下面的方式
则需要对DataGridView控件做相应设置:
注意设置DataPropertyName与表的列名相对应