|字号 订阅
代码一: private void Form1_Load(object sender, EventArgs e) { dataGridView1.DataSource = GetData(); }
private DataTable GetData() { DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection("ConnectionString")) using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.CommandText = "SELECT * FROM Customers";
connection.Open(); using (SqlDataReader reader = command.ExecuteReader (CommandBehavior.CloseConnection)) { dt.Load(reader); } }
return dt; }
代码二: private void Form1_Load(object sender, EventArgs e) { DataTable dt = new DataTable(); dt.Load(GetReader()); dataGridView1.DataSource = dt;
}
private IDataReader GetReader() { DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof(string)); dt.Columns.Add("Firstname", typeof(string)); dt.Columns.Add("Lastname", typeof(string));
dt.Rows.Add((new Object[] {"HAYD", "David", "Hayden"}));
return dt.CreateDataReader(); } |