{
/*第一种,使用ADO.net DataSet连接到GridView*/
//1.创建连接字符串和命令字符串
string connectionString = "Data Source=127.0.0.1;Initial Catalog=Northwind;Integrated Security=True";
string commandString = "Select * From Customers";
//2.为SQLDataAdapter构造函数传递一个字符串
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, connectionString);
//3.创建一个DataSet
DataSet dataSet = new DataSet();
//4.填充DataSet对象
dataAdapter.Fill(dataSet,"Customers");
//5.从DataSet中获取DataTable
DataTable dataTable = dataSet.Tables["Customers"];
//6.绑定到Gridview
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
/*第二种,使用ADO.net SqlDataRead连接到GridView*/
//1.创建连接字符串和命令字符串
string connectionString = "Data Source=127.0.0.1;Initial Catalog=Northwind;Integrated Security=True";
string commandString = "Select * From Customers";
//2.创建链接对象
SqlConnection conn = new SqlConnection(connectionString);
//3.创建命令对象
SqlCommand command = new SqlCommand(commandString);
//4.打开连接
try
{
//打开连接
conn.Open;
//为命令附加连接
command.Connection = conn;
//获取Data Reader
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
//绑定到GridView
GridView1.DataSource = reader;
GridView1.DataBind();
}
finally
{
conn.Close();//关闭连接
}
}