# [C#]DataTable 基礎 ###### tags: `c#` `DataTable` `DataSet` `ASP.Net` `Visual Studio` > [time= 2019 11 07 ] > 原文 & 參考: > https://dotblogs.com.tw/chjackiekimo/2014/04/03/144606 <br> 要先建立DataTable物件 ```csharp= Using System.Data; DataTable dt = new DataTable("StudentData"); ``` <br><br><br> 新增DataColumns ```csharp= 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; ``` <br><br><br> 讓DataGridView的資料來源設定為dt ```csharp= dataGridView1.DataSource = dt; ```  此時我們已經建立好DataColumns,接著要透過DataRow來新增資料 <br><br><br> 透過DataRow來新增資料 ```csharp= //DataRow 沒有New DataRow row; //切記 !! DataTable 要產生Row時,必須使用NewRow這個方法 //可以把它想成為將dt產生一個新的列 row = dt.NewRow(); ``` <br><br><br> 設定值 ```csharp= //隨機產生成績 (放全域) 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")); ``` <br><br><br> 最後將DataRow新增到Table裡 ```csharp= dt.Rows.Add(row); ```  完成 <br><br><br> 當使用DataRow時,可以直接指定欄位名 ex : row["Math"] 或者指定索引值 row[2] 都可以 透過DataRow新增資料還有第二個方法 ```csharp= 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")) }); ``` 這樣也可以,不過要確保欄位順序的問題。
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.