摘要:使用DataTable
新增:
DataTable dataTble = new DataTable();
加入欄位:
DataTble.Columns.Add("Columns_NAME",System.Type.GetType("System.String"))
刪除欄位:
DataTble .Rows[dataTableNum].Delete();
經由Data Row加入:
DataRow workRow = dataTble .NewRow();
workRow["RowName"] ="Sample" ;
workRow["RowData"] = 1;
dtDate.Rows.Add(workRow);
直接由SQL加入:
sqlCon = new SqlConnection(strCon);
sqlCom = new SqlCommand();
sqlCom.Connection = sqlCon;
sqlCom.CommandText = "select_v";
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCon.Open();
sdr = sqlCom.ExecuteReader();
dt = new DataTable();
dataTble .Load(sdr);
整列複製:
DataTable dt2 = new DataTable();
dt2 = dataTble .Copy();//複製
dt2.Rows.Clear();
dt2.ImportRow(dataTble .Rows[0]);//加入第一行
簡單排序:
DataView dvTemp = dataTble .DefaultView;
dvTemp.Sort = "RowData, RowName ";
dvTemp.Sort = "RowData DESC, RowName DESC ";//倒排序
dataTble = dvTemp.ToTable();
設定單一主鍵:
dt.PrimaryKey = new DataColumn[] { dt.Columns["RowName"] };
dt.PrimaryKey = new DataColumn[] { dt.Columns["RowName"], dt.Columns["RowData"] };
搜尋單一條件:
DataRow dr = dt.Rows.Find("條件");
object[] search = new object[] { "條件1", "條件2" };
DataRow dr = dt.Rows.Find(search);
修改搜尋條件內的某個欄位的資料:
dt.Rows.Find("條件").SetField("RowName","要更新的資料");
Data Grid View內容轉為Data Table:
public DataTable DataGridView_To_DataTable(DataGridView dataGridView)
{
DataTable dt = new DataTable();
DataColumn dc;
for (int i = 0; i < dataGridView.Columns.Count; i++)
{
dc = new DataColumn();
dc.ColumnName = dataGridView.Columns[i].Name.ToString();
dt.Columns.Add(dc);
}
for (int j = 0; j < dataGridView.Rows.Count - 1; j++)
{
DataRow dr = dt.NewRow();
for (int k = 0; k < dataGridView.Columns.Count; k++)
{
dr[k] = dataGridView.Rows[j].Cells[k].Value;
}
dt.Rows.Add(dr);
}
return dt;
}