// 第一種,連線資料庫
// 要加上 using System.Data.SqlClient;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("Data Source=資料庫連線字串;Initial Catalog=資料庫名稱;Persist Security Info=True;User ID=資料庫帳號;Password=資料庫密碼");
string query = "SELECT * FROM [MyData] ORDER BY [MyDataNo]";
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter dat = new SqlDataAdapter();
dat.SelectCommand = cmd;
dat.Fill(dt);
dat.Dispose();
conn.Close();
dataGridView1.DataSource = dt;
// 第二種,自己建立 DataTable 內容
DataTable dt = new DataTable();
DataColumn colItem = new DataColumn("item", Type.GetType("System.String"));
dt.Columns.Add(colItem);
DataRow NewRow;
for (int i = 1; i <= 10; i++)
{
NewRow = dt.NewRow();
NewRow["item"] = "Item-" + i;
dt.Rows.Add(NewRow);
}
dataGridView1.DataSource = dt;
留言列表