Try   HackMD

[C#]DataTable 基礎

tags: c# DataTable DataSet ASP.Net Visual Studio

2019 11 07

原文 & 參考:
https://dotblogs.com.tw/chjackiekimo/2014/04/03/144606


要先建立DataTable物件

Using System.Data; DataTable dt = new DataTable("StudentData");




新增DataColumns

dt.Columns.Add("StudentID", typeof(String)); dt.Columns.Add("StudentName", typeof(String)); dt.Columns.Add("Math", typeof(Double)); dt.Columns.Add("Eng", typeof(Double)); //只有String 才要設定長度 //StudentID dt.Columns["StudentID"].MaxLength = 10;//長度 dt.Columns["StudentID"].AllowDBNull = false;//不能空值 dt.Columns["StudentID"].Unique = true;//建立唯一性 //StudnetName dt.Columns["StudentName"].MaxLength = 10; dt.Columns["StudentName"].AllowDBNull = false;




讓DataGridView的資料來源設定為dt

dataGridView1.DataSource = dt;

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

此時我們已經建立好DataColumns,接著要透過DataRow來新增資料




透過DataRow來新增資料

//DataRow 沒有New DataRow row; //切記 !! DataTable 要產生Row時,必須使用NewRow這個方法 //可以把它想成為將dt產生一個新的列 row = dt.NewRow();




設定值

//隨機產生成績 (放全域) Random rd = new Random(); //產生順序ID (放全域) int G_studentID = 0; row["StudentID"] = "S00" + (++G_studentID); row["StudentName"] = G_studentID; row["Math"] = Double.Parse( (rd.NextDouble() * 100.0).ToString("0.00")); row["Eng"] = Double.Parse((rd.NextDouble() * 100.0).ToString("0.00"));




最後將DataRow新增到Table裡

dt.Rows.Add(row);

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

完成




當使用DataRow時,可以直接指定欄位名

ex : row["Math"] 或者指定索引值 row[2] 都可以

透過DataRow新增資料還有第二個方法

DataRow row; row = dt.NewRow(); dt.Rows.Add(new Object[] { "S00" + (++G_studentID), G_studentID, Double.Parse((rd.NextDouble() * 100.0).ToString("0.00")), Double.Parse((rd.NextDouble() * 100.0).ToString("0.00")) });

這樣也可以,不過要確保欄位順序的問題。