C# DataTable(資料物件) 純手工建立 [C# datatable new row]

C# DataTable(資料物件) 純手工建立 [C# datatable new row]

C# DataTable(資料物件) 純手工建立 [C# datatable new row]


資料來源: https://goodlucky.pixnet.net/blog/post/47820264-%5Bc%23%5D-datatable-%E6%96%B0%E5%A2%9E%E8%B3%87%E6%96%99%E5%88%97


https://goodlucky.pixnet.net/blog/post/47820276-%5Bc#%5D%20%E8%87%AA%E8%A1%8C%E5%AE%9A%E7%BE%A9DataTable%E7%9A%84%E6%AC%84%E4%BD%8D%E5%8F%8A%E5%9E%8B%E6%85%8B


https://vimsky.com/zh-tw/examples/detail/csharp-method-system.data.datatable.newrow.html


範例01.

DataTable dtTable = new DataTable();
DataRow row;

// 建立欄位
dtTable.Columns.Add("JOB_ID", typeof(int));
dtTable.Columns.Add("JOB_TITLE", typeof(string));

// 新增資料到DataTable
for (int i = 0; i < 10; i++)
{
	row = dtTable.NewRow();
	row["JOB_ID"] = i;
	row["JOB_TITLE"] = "title " + i.ToString();
	dtTable.Rows.Add(row);
}

GridView1.DataSource = dtTable;
GridView1.DataBind();


範例02.

private void MakeDataTableAndDisplay()
{
   // Create new DataTable and DataSource objects.
   DataTable table = new DataTable();

   // Declare DataColumn and DataRow variables.
   DataColumn column;
   DataRow row; 
   DataView view;

   // Create new DataColumn, set DataType, ColumnName and add to DataTable.    
   column = new DataColumn();
   column.DataType = System.Type.GetType("System.Int32");
   column.ColumnName = "id";
   table.Columns.Add(column);

   // Create second column.
   column = new DataColumn();
   column.DataType = Type.GetType("System.String");
   column.ColumnName = "item";
   table.Columns.Add(column);

   // Create new DataRow objects and add to DataTable.    
   for(int i = 0; i < 10; i++)
   {
	   row = table.NewRow();
	   row["id"] = i;
	   row["item"] = "item " + i.ToString();
	   table.Rows.Add(row);
   }

   // Create a DataView using the DataTable.
   view = new DataView(table);

   // Set a DataGrid control's DataSource to the DataView.
   dataGrid1.DataSource = view;
}


範例03.(欄位型態指定)

    DataTable table = new DataTable();
    table.Columns.Add("Weight", typeof(int));
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Breed", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *