public static DataTable RemoveDuplicates(DataTable dt, DataColumn[] keyColumns, string SavePath, string currentMapping) { int rowNdx = 0; var res = new List<DataTable>(); DataTable duplicatesTable = dt.Clone(); var qFields = string.Join(", ", keyColumns.Select(x => "it[\"" + x.ColumnName + "\"] as " + x.ColumnName.Replace(" ","") + "")); var q = dt.AsEnumerable() .AsQueryable() .GroupBy("new(" + qFields + ")", "it") .Select("new (it as Data)"); var dtemp = dt.Clone(); foreach (dynamic d in q) { // dtemp.Rows.Add(d.Data.First().ItemArray()); rowNdx = 0; foreach (var row in d.Data) { if (rowNdx == 0) { dtemp.Rows.Add(row.ItemArray); } else { duplicatesTable.Rows.Add(row.ItemArray); } rowNdx++; } } string newFileName = string.Format("{0}{1}", "test", rowNdx); FileSaveHelper.ExportDataTable(duplicatesTable, string.Format("{0}\\{1}", SavePath, currentMapping + "_Duplicates.xlsx")); return dtemp; //while (rowNdx < tbl.Rows.Count - 1) //{ // DataRow[] dups = FindDups(tbl, rowNdx, keyColumns); // if (dups.Length > 0) // { // foreach (DataRow dup in dups) // { // duplicatesTable.ImportRow(dup); // tbl.Rows.Remove(dup); // } // tbl.Rows.Add(dups.FirstOrDefault()); // } // else // { // rowNdx++; // } //} // return duplicatesTable; }
/// <summary> /// �Ƚ�����DataTable���ݣ��ṹ��ͬ�� /// </summary> /// <param name="dt1">�������ݿ��DataTable</param> /// <param name="dt2">�����ļ���DataTable</param> /// <param name="keyField">�ؼ��ֶ���</param> /// <param name="dtRetAdd">�������ݣ�dt2�е����ݣ�</param> /// <param name="dtRetDif1">��ͬ�����ݣ����ݿ��е����ݣ�</param> /// <param name="dtRetDif2">��ͬ�����ݣ�ͼ2�е����ݣ�</param> /// <param name="dtRetDel">ɾ�������ݣ�dt2�е����ݣ�</param> public void CompareDt(DataTable dt1, DataTable dt2, string keyField, out DataTable dtRetAdd, out DataTable dtRetDif1, out DataTable dtRetDif2, out DataTable dtRetDel) { //Ϊ�����������ṹ dtRetDel = dt1.Clone(); dtRetAdd = dtRetDel.Clone(); dtRetDif1 = dtRetDel.Clone(); dtRetDif2 = dtRetDel.Clone(); int colCount = dt1.Columns.Count; DataView dv1 = dt1.DefaultView; DataView dv2 = dt2.DefaultView; //���Ե�һ����Ϊ���գ����ڶ����������˻���ɾ���� foreach (DataRowView dr1 in dv1) { dv2.RowFilter = keyField + " = '" + dr1[keyField].ToString() + "'"; if (dv2.Count > 0) { if (!CompareUpdate(dr1, dv2[0]))//�Ƚ��Ƿ��в�ͬ�� { dtRetDif1.Rows.Add(dr1.Row.ItemArray);//��ǰ dtRetDif2.Rows.Add(dv2[0].Row.ItemArray);//�ĺ� // dtRetDif2.Rows[dtRetDif2.Rows.Count - 1]["FID"] = dr1.Row["FID"];//��ID���������ļ��ı����Ϊ����IDȫ��==0 continue; } } else { //�Ѿ���ɾ���� dtRetDel.Rows.Add(dr1.Row.ItemArray); } } //�Ե�һ����Ϊ���գ�����¼�Ƿ��������� dv2.RowFilter = "";//������� foreach (DataRowView dr2 in dv2) { dv1.RowFilter = keyField + " = '" + dr2[keyField].ToString() + "'"; if (dv1.Count == 0) { //������ dtRetAdd.Rows.Add(dr2.Row.ItemArray); } } }
public static DataTable SortLogicalTable(DataTable TableSort, string FieldSort) { if(TableSort==null)return null; DataTable dtBK = TableSort.Clone(); try { DataRow[] rows = new DataRow[TableSort.Rows.Count]; TableSort.Rows.CopyTo(rows, 0); Array.Sort(rows, new DataRowLogicalComparer(FieldSort)); foreach (DataRow r in rows) { dtBK.ImportRow(r); } if (TableSort.DataSet != null) { DataSet ds = new DataSet(); ds.Tables.Add(dtBK); } return dtBK; } catch { } return TableSort; }
private DataTable GetICTableWLevel(ref System.Data.DataTable table) { DataTable RetVal; DataRow NewRow; DataRow[] Rows; int Level = 0; table.Constraints.Clear(); //- Allow db null table.Columns[IndicatorClassifications.ICType].AllowDBNull = true; //Step 1: Set indicator classification levels table.Columns.Add(LanguageKeys.Level, System.Type.GetType("System.Int32")); this.SetIndicatorClassificationLevel(table, -1, 0); //Step 2: Get maximum level from table table.DefaultView.Sort = LanguageKeys.Level + " DESC"; if (table.Rows.Count > 0) { this.MaxLevel = Convert.ToInt32(table.DefaultView.ToTable().Rows[0][LanguageKeys.Level]); } else { this.MaxLevel = 1; } //Step 2: Create New Data Table to fill the list view RetVal = table.Clone(); //insert columns for classification level info. for (Level = 1; Level <= this.MaxLevel; Level++) { RetVal.Columns.Add(LanguageKeys.Level + " " + Level); } //insert rows into new table foreach (DataRow Row in table.Rows) { Rows = RetVal.Select(IndicatorClassifications.ICNId + " =" + Row[IndicatorClassifications.ICParent_NId].ToString()); NewRow = RetVal.NewRow(); NewRow[IndicatorClassifications.ICNId] = Row[IndicatorClassifications.ICNId]; NewRow[IndicatorClassifications.ICParent_NId] = Row[IndicatorClassifications.ICParent_NId]; NewRow[IndicatorClassifications.ICName] = Row[IndicatorClassifications.ICName].ToString(); NewRow[IndicatorClassifications.ICGlobal] = Row[IndicatorClassifications.ICGlobal]; NewRow[IndicatorClassifications.ICInfo] = Row[IndicatorClassifications.ICInfo]; NewRow[IndicatorClassifications.ICGId] = Row[IndicatorClassifications.ICGId]; NewRow[LanguageKeys.Level] = Row[LanguageKeys.Level]; NewRow[LanguageKeys.Level + " " + Convert.ToInt32(Row[LanguageKeys.Level])] = Row[IndicatorClassifications.ICName].ToString(); RetVal.Rows.Add(NewRow); } RetVal.AcceptChanges(); this.SetIndicatorClassificationLevelName(RetVal); RetVal.DefaultView.Sort = IndicatorClassifications.ICNId; return(RetVal); }
public static System.Data.DataTable GetDataTableDynamic(int AtSegment) { InitialPage(); if (AtSegment < _totalpages) { Segment = AtSegment * _itemsonpage; Offset = _itemsonpage; } else if (AtSegment == _totalpages) { Segment = (_parrity)? AtSegment * _itemsonpage : (AtSegment - 1) * _itemsonpage; Offset = _itemsonlastpage; } else { Segment = 0; Offset = _itemsonpage; } System.Data.DataTable DtableDynamic = tablestatic.Clone(); for (int i = Segment; i < Segment + Offset; i++) { if (i == _totalitems) { break; } DtableDynamic.ImportRow(tablestatic.Rows[i]); } _currentpages = AtSegment; return(DtableDynamic); }
public static DataTable CloneTable(DataTable originalTable) { DataTable newTable; newTable = originalTable.Clone(); return newTable; }
private void BindReferrers(string day) { string filename = Server.MapPath(BlogSettings.Instance.StorageLocation + "Log/" + day + ".xml"); if (File.Exists(filename)) { DataSet ds = new DataSet(); ds.ReadXml(filename); DataTable table = new DataTable(); table.Columns.Add("url", typeof(string)); table.Columns.Add("shortUrl", typeof(string)); table.Columns.Add("hits", typeof(int)); DataTable spamTable = table.Clone(); foreach (DataRow row in ds.Tables[0].Rows) { DataRow newRow = table.NewRow(); if (row.Table.Columns.Contains("isSpam") && row["isSpam"].ToString().ToLowerInvariant() == "true") newRow = spamTable.NewRow(); newRow["url"] = Server.HtmlEncode(row["address"].ToString()); newRow["shortUrl"] = MakeShortUrl(row["address"].ToString()); newRow["hits"] = int.Parse(row["url_text"].ToString()); if (row.Table.Columns.Contains("isSpam") && row["isSpam"].ToString().ToLowerInvariant() == "true") spamTable.Rows.Add(newRow); else table.Rows.Add(newRow); } BindTable(table, grid); BindTable(spamTable, spamGrid); } }
/// <summary> /// Clones the tables in the database and adds them to the original tables List. /// </summary> /// <param name="tableNames">The names of all the tables in the database you need to clone</param> /// <returns>List of tables that were cloned</returns> private List <DataTable> GetDataTableClones(List <string> tableNames) { _originalTables = new List <DataTable>(); var tableClones = new List <DataTable>(); using (var con = new SqlConnection(_connectionString)) { foreach (string name in tableNames) { using (var com = new SqlCommand("SELECT * FROM " + name, con)) { DataTable table = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(com); da.FillSchema(table, SchemaType.Source); da.Fill(table); _originalTables.Add(table); tableClones.Add(table.Clone()); } } } return(tableClones); }
public static DataTable ConvertTableType(DataTable dt, Dictionary<string, Type> types) { DataTable newDt = dt.Clone(); //convert all columns' datatype newDt.TableName = dt.TableName; foreach (DataColumn dc in newDt.Columns) { if (types.ContainsKey(dc.ColumnName)) { dc.DataType = types[dc.ColumnName]; } } //import data from original table //foreach (DataRow dr in dt.Rows) //{ // newDt.ImportRow(dr); //} FillData(dt, newDt); dt.Dispose(); return newDt; }
public static DataTable SortDataTable(DataTable dt, string sort) { DataTable newDT = dt.Clone(); int rowCount = dt.Rows.Count; DataRow[] foundRows = dt.Select(null, sort); // Sort with Column name for (int i = 0; i < rowCount; i++) { object[] arr = new object[dt.Columns.Count]; for (int j = 0; j < dt.Columns.Count; j++) { arr[j] = foundRows[i][j]; } DataRow data_row = newDT.NewRow(); data_row.ItemArray = arr; newDT.Rows.Add(data_row); } //clear the incoming dt dt.Rows.Clear(); for (int i = 0; i < newDT.Rows.Count; i++) { object[] arr = new object[dt.Columns.Count]; for (int j = 0; j < dt.Columns.Count; j++) { arr[j] = newDT.Rows[i][j]; } DataRow data_row = dt.NewRow(); data_row.ItemArray = arr; dt.Rows.Add(data_row); } return dt; }
private void FenYe(System.Data.DataTable dataTable) { // if (oo != -1) // { // num = oo; // } System.Data.DataTable dt = dataTable.Clone(); //复制原数据的结构 rows = dataTable.Rows.Count; //总行数 sum = rows % ii == 0 ? rows / ii : (rows / ii) + 1; //总页数=总行数/每页的行数(如果除不尽则+1) if (sum == 0) { sum++; } int ks = (num * ii) - ii; //开始行数(当前页数*每页的行数)-每页的行数 int js = num * ii; //结束行数 if (num == sum) { js = ks + (rows - ((num - 1) * ii)); //当最后一页时,结束的行数 = 开始行数 + (总行数 - ((总页数-1) * 每页的行数)) } //实现分页 if (rows != 0) //必须要有一条记录 { for (int i = ks; i < js; i++) { dt.ImportRow(dataTable.Rows[i]); //复制行 } } label6.Text = num.ToString() + "/" + sum.ToString(); }
static DataRowCollection LoadWorksheetInDataTable(string fileName = null, string sheetName = null) { System.Data.DataTable sheetData = new System.Data.DataTable(); DataRowCollection results = null; using (System.Data.OleDb.OleDbConnection conn = returnConnection(fileName)) { conn.Open(); System.Data.OleDb.OleDbDataAdapter sheetAdapter = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", conn); sheetAdapter.Fill(sheetData); results = sheetData.Clone().Rows; } foreach (DataRow dr in sheetData.Rows) { foreach (string item in KeywordsSelected) { if (dr.Field <string>(ColumnName).Trim().Contains(item)) { results.Add(dr.ItemArray); } } } return(results); }
///<summary> ///绑定数据到GridView,当表格数据为空时显示表头 ///</summary> ///<param name="gridview"></param> ///<param name="table"></param> public static void GridViewDataBind(GridView gridview, DataTable table) { //记录为空重新构造Gridview EmptyText = Resources.MyGlobal.NoDataText; if (table.Rows.Count == 0) { table = table.Clone(); table.Rows.Add(table.NewRow()); int columnCount = table.Columns.Count; gridview.DataSource = table; gridview.DataBind(); gridview.Rows[0].Cells.Clear(); gridview.Rows[0].Cells.Add(new TableCell()); gridview.Rows[0].Cells[0].ColumnSpan = columnCount; gridview.Rows[0].Cells[0].Text = EmptyText; gridview.Rows[0].Cells[0].Style.Add("text-align", "center"); gridview.Rows[0].Cells[0].Style.Add("color", "red"); gridview.Rows[0].Style.Add("height", "24px"); //gridview.HeaderRow.Enabled = false; } else { //数据不为空直接绑定 gridview.DataSource = table; gridview.DataBind(); } //重新绑定取消选择 gridview.SelectedIndex = -1; }
/// <summary> /// 转换成和数据库一致的datatable /// </summary> /// <param name="tb"></param> /// <returns></returns> private DataTable ConvertDatatTableForDB(DataTable tb) { DataTable dt = new DataTable(); try { dt = tb.Clone(); foreach (DataColumn col in dt.Columns) { switch (col.ColumnName) { case "data_value": col.DataType = typeof(string); break; } } foreach (DataRow row in tb.Rows) { DataRow new_row = dt.NewRow(); new_row["data_value"] = row["data_value"]; dt.Rows.Add(new_row); } return(dt); } catch (Exception ex) { } return(null); }
public static DataTable SetPage(DataTable dt, int currentPageIndex, int pageSize) { if (currentPageIndex == 0) { return dt; } DataTable newdt = dt.Clone(); int rowbegin = (currentPageIndex - 1) * pageSize; //当前页的第一条数据在dt中的地位 int rowend = currentPageIndex * pageSize; //当前页的最后一条数据在dt中的地位 if (rowbegin >= dt.Rows.Count) { return newdt; } if (rowend > dt.Rows.Count) { rowend = dt.Rows.Count; } DataView dv = dt.DefaultView; for (int i = rowbegin; i <= rowend - 1; i++) { newdt.ImportRow(dv[i].Row); } return newdt; }
/// <summary> /// 绑定数据到GridView,当表格数据为空时显示表头 /// </summary> /// <param name="gridview"></param> /// <param name="table">not null</param> public static void GridViewDataBind(GridView gridview, DataTable table) { if (table == null) throw new NullReferenceException(); //记录为空重新构造Gridview if (table.Rows.Count == 0) { table = table.Clone(); table.Rows.Add(table.NewRow()); gridview.DataSource = table; gridview.DataBind(); int columnCount = table.Columns.Count; gridview.Rows[0].Cells.Clear(); gridview.Rows[0].Cells.Add(new TableCell()); gridview.Rows[0].Cells[0].ColumnSpan = columnCount; gridview.Rows[0].Cells[0].Text = EmptyText; gridview.Rows[0].Cells[0].Style.Add("text-align", "center"); } else { //数据不为空直接绑定 gridview.DataSource = table; gridview.DataBind(); } //重新绑定取消选择 gridview.SelectedIndex = -1; }
private void carregarDttUserCampo() { dtUserCampo = user.getCamposUsuario(); dtAtual = dtUserCampo.Clone(); dtAtual.Clear(); dtgvCampos.DataSource = dtAtual; }
/// <summary> /// 获取表数据 /// </summary> /// <param name="startIndex">开始的位置(由0开始)</param> /// <param name="count">要查询的条数(传入0为查全部)</param> /// <param name="select">查询条件</param> /// <param name="dt">DataTable数据集</param> /// <returns>结果集</returns> public static DataTable Select(int startIndex, int count, string select, DataTable dt) { DataRow[] dr = dt.Select(select); int length = startIndex + count; DataTable returndt = dt.Clone(); if (count == 0) { count = dr.Length; } else if (count > dr.Length) { count = dr.Length; } else if (dr.Length < length) { for (int i = startIndex; i < dr.Length; i++) { returndt.ImportRow(dr[i]); } } else { for (int i = startIndex; i < length; i++) { returndt.ImportRow(dr[i]); } } return returndt; }
private void LoadData() { int nStartPos = 0; //当前页面开始记录行 int nEndPos = 0; //当前页面结束记录行 if (dtInfo.Rows.Count != 0) { System.Data.DataTable dtTemp = dtInfo.Clone(); //克隆DataTable结构框架 if (pageCurrent == pageCount) { nEndPos = nMax; } else { nEndPos = pageSize * pageCurrent; } nStartPos = nCurrent; lblPageCount.Text = "/" + pageCount.ToString(); txtCurrentPage.Text = Convert.ToString(pageCurrent); //从元数据源复制记录行 for (int i = nStartPos; i < nEndPos; i++) { dtTemp.ImportRow(dtInfo.Rows[i]); nCurrent++; } bindingSource1.DataSource = dtTemp; bindingNavigator1.BindingSource = bindingSource1; dgvInfo.DataSource = bindingSource1; dgvInfo.Visible = true; } }
private DataTable AddChild(System.Data.DataTable _tb) { DataTable _Tbtmp = _tb.Copy(); foreach (DataRow _RootDr in _Tbtmp.Rows) { string _RootMaSP = _RootDr["MaSP"].ToString(); string _RootCD = _RootDr["MaCongDoan"].ToString(); string _RootCD2 = ""; if (_RootDr["MaCongDoanMe"] != DBNull.Value) { _RootCD2 = _RootDr["MaCongDoanMe"].ToString(); } double _soluong = double.Parse(_RootDr["Soluong"].ToString()); double _thutu = double.Parse(_RootDr["Thutu"].ToString()); string sql = "select b.MaCongdoan, a.MaCongdoan as MaCongdoanMe, b.MaSP, b.MaWC, b.Thutu," + _soluong.ToString() + "*a.Soluong as Soluong,dbo.RoundUp(" + _soluong.ToString() + ",b.Lot) as SLThaotac, dbo.RoundUp(" + _soluong.ToString() + ",b.Lot)*(b.SetupTime + b.MoveTime+b.RunTime*b.Lot) as LenOfRouting, b.ToTalTime, b.Lot,(b.SetupTime + b.MoveTime+b.RunTime*b.Lot) as LotTime,0.0 as Stime,0.0 as Etime,0.0 as OrgETime " + "from dfRouting b LEFT join dfSPTree a ON a.MaVT=b.MaSP WHERE (a.masp='" + _RootMaSP + "' and b.Thutu=0 and a.MaCongdoan='" + _RootCD + "')" + "union all " + "select b.MaCongdoan, '" + _RootCD + "' as MaCongdoanMe, b.MaSP, b.MaWC, b.Thutu," + _soluong.ToString() + " as Soluong,dbo.RoundUp(" + _soluong.ToString() + ",b.Lot) as SLThaotac,dbo.RoundUp(" + _soluong.ToString() + ",b.Lot)*(b.SetupTime + b.MoveTime+b.RunTime*b.Lot) as LenOfRouting, b.ToTalTime, b.Lot,(b.SetupTime + b.MoveTime+b.RunTime*b.Lot) as LotTime,0.0 as Stime,0.0 as Etime,0.0 as OrgETime " + "from dfRouting b LEFT join dfSPTree a ON a.MaVT=b.MaSP WHERE (b.MaSP='" + _RootMaSP + "' and b.Thutu=" + (_thutu + 1).ToString() + " and a.MaCongdoan='" + _RootCD2 + "') "; DataTable _tbBTP = db.GetDataTable(sql); DataTable _ChildTb = _tb.Clone(); _ChildTb = AddChild(_tbBTP); _tb = AddChildTb(_tb, _ChildTb); } return(_tb); }
public static void BindCombo( ref DropDownList Cbo , DataTable Dt , string Value , string Text , object Default_Value , string Default_Text ) { DataTable Dt_Bind = Dt.Clone(); DataRow Dr = Dt_Bind.NewRow(); Dr[Value] = Default_Value; Dr[Text] = Default_Text; Dt_Bind.Rows.Add(Dr); foreach( DataRow Inner_Dr in Dt.Rows) { DataRow Nr = Dt_Bind.NewRow(); Nr[Value] = Inner_Dr[Value]; Nr[Text] = Inner_Dr[Text]; Dt_Bind.Rows.Add(Nr); } BindCombo(ref Cbo, Dt_Bind, Value, Text); }
/// <summary> /// Sorts the <see cref="System.Data.DataTable"/>. /// </summary> /// <param name="sourceTable">The source table.</param> /// <param name="sortColumn">The column to sort by.</param> /// <param name="order">The <see cref="Tools.Common.SortOrder"/>.</param> /// <param name="copyIfNoSort">Should only be true when one table owner is assumed /// other time and space.</param> /// <returns></returns> public static DataTable SortDataTable(DataTable sourceTable, string sortColumn, SortOrder order, bool copyIfNoSort) { if (String.IsNullOrEmpty(sortColumn)) { // copyIfNoSort make the semantic more stable, even if there is no sort required // the copy is returned, so the caller may assume same level of independence. if (copyIfNoSort) return sourceTable.Copy(); return sourceTable; } DataTable targetTable = sourceTable.Clone(); DataRow[] sourceRows = sourceTable.Select(null, ("[" + sortColumn + "] " + order.ToString()).TrimEnd(' ')); for (int i = 0; i < sourceRows.Length; i++) { DataRow newRow = targetTable.NewRow(); newRow.ItemArray = sourceRows[i].ItemArray; targetTable.Rows.Add(newRow); } return targetTable; }
private void Get_Tarifas() { string query = frete.Properties.Resources.sql_Select_TarifasPedido; List<string> campos = new List<string>(); campos.Add("idtarifas"); campos.Add("transportadora"); campos.Add("cidade"); DBConnect dbc = new DBConnect(); dtDisponiveis = dbc.Select(query, campos.Count, campos); dtDisponiveis.Columns.Add("copiado", typeof(bool)); foreach (DataRow dr in dtDisponiveis.Rows) dr["copiado"] = false; dgv_Disponiveis.DataSource = dtDisponiveis; dtSelecionados = dtDisponiveis.Clone(); dtSelecionados.Columns.Add("index_disp", typeof(int)); dgv_Selecionados.DataSource = dtSelecionados; }
public static DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize) { if (PageIndex == 0) return dt; DataTable newdt = dt.Clone(); //newdt.Clear(); int rowbegin = (PageIndex - 1) * PageSize; int rowend = PageIndex * PageSize; if (rowbegin >= dt.Rows.Count) return newdt; if (rowend > dt.Rows.Count) rowend = dt.Rows.Count; for (int i = rowbegin; i <= rowend - 1; i++) { DataRow newdr = newdt.NewRow(); DataRow dr = dt.Rows[i]; foreach (DataColumn column in dt.Columns) { newdr[column.ColumnName] = dr[column.ColumnName]; } newdt.Rows.Add(newdr); } return newdt; }
/// <summary> /// DataTable倒序 /// </summary> /// <param name="dt">源DataTable</param> public static DataTable Reverse(DataTable dt) { var tmpDt = dt.Clone(); for (var i = dt.Rows.Count - 1; i >= 0; i--) { tmpDt.ImportRow(dt.Rows[i]); } return tmpDt; }
private void btnInGiayBao_Click(object sender, EventArgs e) { if (grvSVTrungTuyen != null && grvSVTrungTuyen.DataRowCount > 0) { if (cmbTrinhDo.ItemIndex >= 0 && cmbKhoaHoc.ItemIndex >= 0) { DataTable dtTrungTuyen = dtSinhVien.Clone(); for (int i = 0; i < grvSVTrungTuyen.DataRowCount; i++) { dtTrungTuyen.ImportRow(grvSVTrungTuyen.GetDataRow(i)); } oBSV_SinhVienNhapTruong.XuLyGiayBao(ref dtTrungTuyen, Program.NamHoc, cmbTrinhDo.Text + " - Khóa: " + cmbKhoaHoc.Text); frmReport frm = new frmReport(dtTrungTuyen, "rGiayBaoNhapHoc"); frm.Show(); } else { ThongBao("Bạn cần chọn Trình độ và khóa học."); } } else { ThongBao("Chưa có sinh viên nào trong danh sách."); } }
private void txt_State_County_TextChanged(object sender, EventArgs e) { //if (gridstate.Rows.Count > 0) //{ // DataView dtsearch = new DataView(dtsel); if (txt_State_County.Text != "Search by State County..." && txt_State_County.Text != "") { DataView dtsearch = new DataView(dtselect); // DataView dtsearch = new DataView(dt_Search); var search = txt_State_County.Text.ToString(); dtsearch.RowFilter = "State like '%" + search.ToString() + "%' or County like '%" + search.ToString() + "%' "; dt = dtsearch.ToTable(); System.Data.DataTable temptable1 = dt.Clone(); int startindex = currentpageindex * pagesize; int endindex = (currentpageindex * pagesize) + pagesize; if (endindex > dt.Rows.Count) { endindex = dt.Rows.Count; } for (int i = startindex; i < endindex; i++) { DataRow row = temptable1.NewRow(); Get_Row_Table_Search(ref row, dt.Rows[i]); temptable1.Rows.Add(row); } if (temptable1.Rows.Count > 0) { gridstate.Rows.Clear(); for (int i = 0; i < temptable1.Rows.Count; i++) { gridstate.Rows.Add(); gridstate.Rows[i].Cells[0].Value = i + 1; gridstate.Rows[i].Cells[1].Value = temptable1.Rows[i]["State"].ToString(); gridstate.Rows[i].Cells[2].Value = temptable1.Rows[i]["County"].ToString(); gridstate.Rows[i].Cells[3].Value = temptable1.Rows[i]["Vendor_Id"].ToString(); gridstate.Rows[i].Cells[4].Value = temptable1.Rows[i]["Vendor_State_Id"].ToString(); } lbl_Total_State_County.Text = dt.Rows.Count.ToString(); } else { gridstate.Rows.Clear(); MessageBox.Show("No Records Found"); // Bind_All_State_Info(); txt_State_County.Text = ""; } lblRecordsStatus.Text = (currentpageindex + 1) + " / " + (int)Math.Ceiling(Convert.ToDecimal(dt.Rows.Count) / pagesize); } else { Bind_All_State_Info(); } }
public override DataTable CreateDataTable(string tableName, IList<string> identifiers) { DataTable dataTable = new DataTable(); DataTable dTable = new DataTable(tableName); string query = string.Empty; string delimiter = string.Empty; string[] idArray = null; DataObject dataObject = _dictionary.dataObjects.Where<DataObject>(p => p.tableName == tableName).FirstOrDefault(); IList<string> keyProperties = keyProperties = (from p in dataObject.keyProperties select p.keyPropertyName).ToList<string>(); if (keyProperties.Count > 1) { delimiter = dataObject.keyDelimeter; } IList<string> idList = new List<string>(); if (identifiers != null) { int j = 0; foreach (string identifier in identifiers) { idList.Add(identifier); dataTable = GetDataTable(tableName, idList); idList.Clear(); if (dataTable != null && dataTable.Rows != null) { dTable = dataTable.Clone(); if (dataTable.Rows.Count > 0) dTable.Rows.Add(dataTable.Rows[j].ItemArray); else { DataRow drow = null; for (int i = 0; i < keyProperties.Count; i++) { if (identifier.Contains(delimiter.FirstOrDefault())) { idArray = identifier.Split(delimiter.FirstOrDefault()); } else if (keyProperties.Count == 1) { idArray = identifier.Split(); } } drow = dTable.NewRow(); dTable.Rows.Add(drow); for (int i = 0; i < keyProperties.Count; i++) { drow[keyProperties[i]] = idArray[i]; drow.AcceptChanges(); } } } j++; } } return dTable; }
private static void AppendData(DataTable source, ref DataTable target) { if (target == null) target = source.Clone(); foreach (DataRow row in source.Rows) target.ImportRow(row); }
/// <summary> /// 对DataTable排序 /// </summary> /// <param name="dt">要排序的表</param> /// <param name="sort">要排序的字段</param> public static DataTable Sort(DataTable dt, string sort = "ID DESC") { var rows = dt.Select("", sort); var tmpDt = dt.Clone(); foreach (var row in rows) { tmpDt.ImportRow(row); } return tmpDt; }
private void Bind_General() { System.Data.DataTable temptable = dtselect.Clone(); int start_index = currentpageindex * pagesize; int end_index = currentpageindex * pagesize + pagesize; if (end_index > dtselect.Rows.Count) { end_index = dtselect.Rows.Count; } for (int i = start_index; i < end_index; i++) { DataRow row = temptable.NewRow(); GetRowTable(ref row, dtselect.Rows[i]); temptable.Rows.Add(row); } grd_ActInact.Columns[4].Visible = true; if (temptable.Rows.Count > 0) { grd_ActInact.Rows.Clear(); for (int i = 0; i < temptable.Rows.Count; i++) { grd_ActInact.Rows.Add(); grd_ActInact.Rows[i].Cells[0].Value = i + 1; grd_ActInact.Rows[i].Cells[1].Value = temptable.Rows[i]["Employee_Name"].ToString(); grd_ActInact.Rows[i].Cells[2].Value = temptable.Rows[i]["Role_Name"].ToString(); grd_ActInact.Rows[i].Cells[3].Value = temptable.Rows[i]["User_Name"].ToString(); if (temptable.Rows[i]["User_Avilable"].ToString() == "True") { Active_Inactive = "Inactive"; grd_ActInact.Rows[i].Cells[4].Value = Image.FromFile(@"\\192.168.12.33\Oms-Image-Files\User_Male_Check.png"); } else { Active_Inactive = "Active"; grd_ActInact.Rows[i].Cells[4].Value = Image.FromFile(@"\\192.168.12.33\Oms-Image-Files\User_Male_Delete.png"); } // grd_ActInact.Rows[i].Cells[4].Value = Active_Inactive; grd_ActInact.Rows[i].Cells[5].Value = temptable.Rows[i]["User_id"].ToString(); // grd_ActInact.Rows[i].Cells[4].Style.BackColor = System.Drawing.Color.Red; grd_ActInact.Rows[i].Cells[4].Style.ForeColor = System.Drawing.Color.WhiteSmoke; grd_ActInact.Rows[i].Cells[0].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; grd_ActInact.Rows[i].Cells[4].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; } } else { grd_ActInact.Visible = true; grd_ActInact.DataSource = null; MessageBox.Show("Record not found"); } lblRecordsStatus.Text = (currentpageindex + 1) + "/" + ((int)Math.Ceiling(Convert.ToDecimal(dtselect.Rows.Count) / pagesize)); lbl_Total_Orders.Text = dtselect.Rows.Count.ToString(); }
public virtual System.Data.DataTable Transform(DataTable sourceTable) { DataTable retTable = sourceTable.Clone(); // only clones the structure SortedList<string, string> transposeNames = new SortedList<string, string>(); PrepareColumns(sourceTable, retTable, transposeNames); SortedList<string, DataRow> keyRows = new SortedList<string, DataRow>(); for (int i = 0; i < sourceTable.Rows.Count; i++) { DataRow sourceRow = sourceTable.Rows[i]; // PrepareTransposeKeyKeyColumns(sourceTable, retTable, transposeNames); // Null values are normalized to be an empty string string trKeyName = String.Empty; object sourceNameObject = sourceRow[transposeDefinition.SourceNameColumnName]; if (sourceNameObject != null) { trKeyName = sourceNameObject.ToString(); } string dataKeyName = String.Empty; object dataKeyNameObject = sourceRow[transposeDefinition.KeyColumnName]; if (dataKeyNameObject != null) { dataKeyName = dataKeyNameObject.ToString(); } //** if (!keyRows.ContainsKey(dataKeyName)) { DataRow dr = retTable.NewRow(); keyRows.Add(dataKeyName, dr); retTable.Rows.Add(dr); FillRow(sourceTable, sourceRow, dr, trKeyName); } else { FillRow(sourceTable, sourceRow, keyRows[dataKeyName], trKeyName); } } ReshuffleColumns(retTable, transposeNames); return retTable; }
public static DataRow RegistNewData(DataTable refDataTable, DataRow newDataRow) { DataForm dataForm = new DataForm(newDataRow); dataForm.refDataTable = refDataTable.Clone(); dataForm.ShowDialog(); dataForm.Dispose(); return dataForm.retRow; }
/// <summary> /// Crée un clone d'une DataTable et en importe toutes les DataRows /// </summary> /// <param name="tab">La DataTable à cloner</param> /// <returns>La DataTable clonée et remplie</returns> public static DataTable CloneWithContent(DataTable tab) { DataTable clone = tab.Clone(); foreach (DataRow row in tab.Rows) clone.ImportRow(row); return clone; }
/// <summary> /// 处理DataTable,把DataTable里面的true 或 false 换成文字 /// </summary> /// <param name="dt">要处理的DataTable</param> /// <returns>处理后的DataTable</returns> private System.Data.DataTable ProcessDataTable(System.Data.DataTable dt) { try { if (dt != null && dt.Rows.Count > 0) { bool flag = false; System.Data.DataTable dtClone = dt.Clone(); foreach (DataColumn dc in dtClone.Columns) { if (dc.DataType.Name.ToLower() == "boolean") { dc.DataType = typeof(string); flag = true; } } if (flag == true) { //复制数据到克隆的datatable里 try { foreach (DataRow dr in dt.Rows) { dtClone.ImportRow(dr); } } catch { } dt = dtClone; } for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { if (dt.Rows[i][j].ToString().ToLower() == "true") { dt.Rows[i][j] = "是"; } else if (dt.Rows[i][j].ToString().ToLower() == "false") { dt.Rows[i][j] = ""; } } } } return(dt); } catch (Exception e) { if (!e.Message.Equals("正在中止线程。")) { MessageBox.Show("发生错误,错误信息[" + e.Message + "]", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return(null); } }
public DataTable GetNewDataTable(DataTable dt, string condition, string sortOrder) { var newdt = dt.Clone(); var dr = dt.Select(condition, sortOrder); foreach (var t in dr) { newdt.ImportRow(t); } return newdt; }
/*Me selecciona cuantas lineas quiero que se manden como un TOP EN SQL SERVER*/ public DataTable SelectTopDataRow(DataTable dt, int count) { DataTable dtn = dt.Clone(); for (int i = 0; i < count; i++) { dtn.ImportRow(dt.Rows[i]); } return dtn; }
/// <summary> /// 住所録データ更新 /// </summary> /// <param name="updateDataRow"></param> /// <returns>更新されたデータの行</returns> public static DataRow GetUpdatedData(DataTable refDataTable, DataRow updateDataRow) { if (updateDataRow == null) return null; DataForm dataForm = new DataForm(updateDataRow); dataForm.refDataTable = refDataTable.Clone(); dataForm.ShowDialog(); dataForm.Dispose(); return dataForm.retRow; }
public DataTable ConvertDataType(DataTable source, DataTable dest) { DataTable clone = dest.Clone(); foreach (DataRow dataRow in source.Rows) { var itemArray = dataRow.ItemArray; clone.Rows.Add(itemArray); } return clone; }
/// <summary> /// Applies the filter to the current data. /// </summary> /// public DataTable Apply(DataTable data) { DataTable table = data.Clone(); DataRow[] rows = data.Select(Expression, OrderBy); foreach (DataRow row in rows) table.ImportRow(row); return table; }
private DataTable GetNewDataTable(DataTable dt, string condition) { DataTable newdt = new DataTable(); newdt = dt.Clone(); DataRow[] dr = dt.Select(condition); for (int i = 0; i < dr.Length; i++) newdt.ImportRow((DataRow)dr[i]); return newdt; }
protected void btnPreview_Click(object sender, EventArgs e) { if (dtpStartDate.SelectedDate > DateTime.Now) return; if (dtpStartDate.SelectedDate > dtpEndDate.SelectedDate) return; if (dtpStartDate.SelectedDate.ToString().Trim() == string.Empty || dtpEndDate.SelectedDate.ToString().Trim() == string.Empty) return; TransaksiBKUQuery transBkuQ = new TransaksiBKUQuery(); SaldoAwalCollection saCol = new SaldoAwalCollection(); saCol.LoadAll(); transBkuQ.SelectAll(); transBkuQ.Where(transBkuQ.TransDate >= dtpStartDate.SelectedDate, transBkuQ.TransDate <= dtpEndDate.SelectedDate); TransaksiBKUCollection transBkuCol = new TransaksiBKUCollection(); transBkuCol.Load(transBkuQ); if (transBkuCol.Count > 0) { dt = transBkuQ.LoadDataTable(); dt.Columns.Add("Saldo", typeof(decimal)); DataTable dtCopy = dt.Clone(); foreach (RSCM_BKU_Web.BusinessObjects.SaldoAwal sa in saCol) { dt.Rows.Add("", null, "", "", "", "", 0, 0, false, false, true, sa.SaldoAwal); dtCopy.Rows.Add("", null, "", "", "", "", 0, 0, false, false, true, sa.SaldoAwal); SaldoAwal = Convert.ToDecimal((sa.SaldoAwal)); } foreach (DataColumn dc in dt.Columns) { this.Title = this.Title + " - " + dc.ColumnName; } foreach (DataRow dr in dt.Rows) { SaldoAwal = SaldoAwal + (Convert.ToDecimal(dr["DEBIT_AMOUNT"]) - Convert.ToDecimal(dr["CREDIT_AMOUNT"])); dr["Saldo"] = SaldoAwal; dt.AcceptChanges(); dtCopy.Rows.Add(dr["TRANS_NUMBER"],dr["TRANS_DATE"],dr["DESCRIPT"],dr["KA_CODE"],dr["KA_NAME"],dr["GT_CODE"],dr["DEBIT_AMOUNT"],dr["CREDIT_AMOUNT"],dr["IS_CLOSED"],dr["ISVERIFIED"],dr["IS_ACTIVE"],dr["Saldo"]); } RSCM_BKU_web.Report.LaporanBKU report1 = new LaporanBKU(); report1.ReportParameters[0].Value = dtpStartDate.SelectedDate; report1.ReportParameters[1].Value = dtpEndDate.SelectedDate; report1.DataSource = dtCopy; ReportViewer1.Report = report1; ReportViewer1.RefreshReport(); } else return; }
public static System.Data.DataTable Paging(System.Data.DataTable tb, int pageRowCount, int pageIndex) { var tb2 = tb.Clone(); for (int i = (pageIndex - 1) * pageRowCount; i < pageIndex * pageRowCount; i++) { if (i < tb.Rows.Count) { tb2.Rows.Add(tb.Rows[i].ItemArray); } } return(tb2); }
private void Bind_All_State() { //DataView dtview = new DataView(dt_grid_serach_State_County); DataView dtview = new DataView(dtselect); dt = dtview.ToTable(); System.Data.DataTable temptable = dt.Clone(); // currentpageindex++; int startindex = currentpageindex * pagesize; int endindex = (currentpageindex * pagesize) + pagesize; if (endindex > dt.Rows.Count) { endindex = dt.Rows.Count; } for (int i = startindex; i < endindex; i++) { DataRow row = temptable.NewRow(); Get_Row_Table_Search(ref row, dt.Rows[i]); temptable.Rows.Add(row); } dt_Search = temptable; if (temptable.Rows.Count > 0) { gridstate.Rows.Clear(); for (int i = 0; i < temptable.Rows.Count; i++) { gridstate.Rows.Add(); gridstate.Rows[i].Cells[0].Value = i + 1; gridstate.Rows[i].Cells[1].Value = temptable.Rows[i]["State"].ToString(); gridstate.Rows[i].Cells[2].Value = temptable.Rows[i]["County"].ToString(); gridstate.Rows[i].Cells[3].Value = temptable.Rows[i]["Vendor_Id"].ToString(); gridstate.Rows[i].Cells[4].Value = temptable.Rows[i]["Vendor_State_Id"].ToString(); } lbl_Total_State_County.Text = temptable.Rows.Count.ToString(); } else { //gridstate.Rows.Clear(); //MessageBox.Show("No Records Found"); //Bind_All_State(); //txt_State_County.Text = ""; } lbl_Total_State_County.Text = dt_Search.Rows.Count.ToString(); lblRecordsStatus.Text = (currentpageindex + 1) + " / " + (int)Math.Ceiling(Convert.ToDecimal(dt.Rows.Count) / pagesize); }
public override System.Data.DataTable SelectInstitutes(System.Data.DataTable institutes, List <string> parentInstitues) { DataTable result = institutes.Clone(); foreach (DataRow row in institutes.Rows) { string parentInstitute = row[0].ToString(); if (StringUtil.EqualIgnoreCase(parentInstitues, parentInstitute)) { result.Rows.Add(row.ItemArray); } } return(result); }
private void Filter_State_Data() { System.Data.DataTable tempTable = dtsort.Clone(); int startindex = currentpageindex * pagesize; int endindex = currentpageindex * pagesize + pagesize; if (endindex > dtsort.Rows.Count) { endindex = dtsort.Rows.Count; } for (int i = startindex; i < endindex; i++) { DataRow newrow = tempTable.NewRow(); GetNewRow_State(ref newrow, dtsort.Rows[i]); tempTable.Rows.Add(newrow); } if (tempTable.Rows.Count > 0) { grd_County.Rows.Clear(); for (int i = 0; i < tempTable.Rows.Count; i++) { grd_County.Rows.Add(); grd_County.Rows[i].Cells[0].Value = i + 1; grd_County.Rows[i].Cells[1].Value = tempTable.Rows[i]["State_Name"].ToString(); grd_County.Rows[i].Cells[2].Value = tempTable.Rows[i]["County"].ToString(); grd_County.Rows[i].Cells[3].Value = tempTable.Rows[i]["County_Type"].ToString(); grd_County.Rows[i].Cells[4].Value = tempTable.Rows[i]["State_ID"].ToString(); grd_County.Rows[i].Cells[5].Value = tempTable.Rows[i]["County_ID"].ToString(); grd_County.Rows[i].Cells[6].Value = "View"; grd_County.Rows[i].Cells[7].Value = "Delete"; grd_County.Rows[i].Cells[0].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; grd_County.Rows[i].Cells[3].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; grd_County.Rows[i].Cells[6].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; grd_County.Rows[i].Cells[7].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; } } else { grd_County.Rows.Clear(); grd_County.Visible = true; grd_County.DataSource = null; string title = "Empty!"; MessageBox.Show("No Records Found", title); } lbl_Total_Orders.Text = dtsort.Rows.Count.ToString(); lblRecordsStatus.Text = (currentpageindex + 1) + " / " + (int)Math.Ceiling(Convert.ToDecimal(dtsort.Rows.Count) / pagesize); }
public System.Data.DataTable FiltraDataTable(System.Data.DataTable dtprincipal, string ctrFiltro) { /* Seleccionamos las filas que se correspondan con el identificador */ System.Data.DataRow[] rows = dtprincipal.Select(ctrFiltro); /* Clonamos la estructura del objeto DataTable principal */ System.Data.DataTable dt1 = dtprincipal.Clone(); // Importamos los registros al nuevo DataTable foreach (DataRow row in rows) { dt1.ImportRow(row); } return(dt1); }
private void Bind_filter_data() { System.Data.DataTable temptable = temp.Clone(); int startindex = Currentpageindex * pagesize; int endindex = Currentpageindex * pagesize + pagesize; if (endindex > temp.Rows.Count) { endindex = temp.Rows.Count; } for (int i = startindex; i < endindex; i++) { DataRow row = temptable.NewRow(); GetrowTable_Client(ref row, temp.Rows[i]); temptable.Rows.Add(row); } if (temptable.Rows.Count > 0) { grd_All_Tax_Completed_orders.Rows.Clear(); for (int i = 0; i < temptable.Rows.Count; i++) { grd_All_Tax_Completed_orders.Rows.Add(); grd_All_Tax_Completed_orders.Rows[i].Cells[1].Value = i + 1; grd_All_Tax_Completed_orders.Rows[i].Cells[2].Value = temptable.Rows[i]["Client_Order_Number"].ToString(); grd_All_Tax_Completed_orders.Rows[i].Cells[3].Value = temptable.Rows[i]["Order_Type"].ToString(); grd_All_Tax_Completed_orders.Rows[i].Cells[4].Value = temptable.Rows[i]["Borrower_Name"].ToString(); grd_All_Tax_Completed_orders.Rows[i].Cells[5].Value = temptable.Rows[i]["Address"].ToString(); grd_All_Tax_Completed_orders.Rows[i].Cells[6].Value = temptable.Rows[i]["Assigned_Date"].ToString(); grd_All_Tax_Completed_orders.Rows[i].Cells[7].Value = temptable.Rows[i]["STATE_COUNTY"].ToString(); grd_All_Tax_Completed_orders.Rows[i].Cells[8].Value = temptable.Rows[i]["APN"].ToString(); Column5.Visible = true; if (temptable.Rows[i]["Sending_Date"].ToString() == "") { grd_All_Tax_Completed_orders.Rows[i].Cells[9].Value = "N/A"; } else { grd_All_Tax_Completed_orders.Rows[i].Cells[9].Value = temptable.Rows[i]["Sending_Date"].ToString(); } grd_All_Tax_Completed_orders.Rows[i].Cells[12].Value = temptable.Rows[i]["Order_ID"].ToString(); grd_All_Tax_Completed_orders.Rows[i].Cells[13].Value = temptable.Rows[i]["Sub_ProcessId"].ToString(); } } lbl_Total_Orders.Text = temp.Rows.Count.ToString(); lblRecordsStatus.Text = (Currentpageindex + 1) + " / " + (int)Math.Ceiling(Convert.ToDecimal(temp.Rows.Count) / pagesize); }
private void County_search() { System.Data.DataTable temptable = dtcounty.Clone(); int startindex = currentpageindex * pagesize; int endindex = currentpageindex * pagesize + pagesize; if (endindex > dtcounty.Rows.Count) { endindex = dtcounty.Rows.Count; } for (int i = startindex; i < endindex; i++) { DataRow Row = temptable.NewRow(); GetRowTable_county(ref Row, dtcounty.Rows[i]); temptable.Rows.Add(Row); } if (temptable.Rows.Count > 0) { grd_Services.Rows.Clear(); for (int i = 0; i < temptable.Rows.Count; i++) { grd_Services.AutoGenerateColumns = false; grd_Services.Rows.Add(); grd_Services.Rows[i].Cells[0].Value = i + 1; //grd_Services.Rows[i].Cells[0].Value = i + 1; grd_Services.Rows[i].Cells[1].Value = temptable.Rows[i]["Name"].ToString(); grd_Services.Rows[i].Cells[2].Value = temptable.Rows[i]["Contact_Name"].ToString(); grd_Services.Rows[i].Cells[3].Value = temptable.Rows[i]["Gender"].ToString(); grd_Services.Rows[i].Cells[4].Value = temptable.Rows[i]["Phone_No"].ToString(); grd_Services.Rows[i].Cells[5].Value = temptable.Rows[i]["Email"].ToString(); grd_Services.Rows[i].Cells[6].Value = temptable.Rows[i]["Fax_No"].ToString(); grd_Services.Rows[i].Cells[7].Value = temptable.Rows[i]["Abstractor_Id"].ToString(); grd_Services.Rows[i].Cells[8].Value = "View/Edit"; grd_Services.Rows[i].Cells[9].Value = "View/Edit"; grd_Services.Rows[i].Cells[10].Value = "DELETE"; } } else { grd_Services.Visible = true; grd_Services.Rows.Clear(); grd_Services.DataSource = dtcounty; } lbl_Total_Orders.Text = dtcounty.Rows.Count.ToString(); lblRecordsStatus.Text = (currentpageindex + 1) + " / " + (int)Math.Ceiling(Convert.ToDecimal(dtcounty.Rows.Count) / pagesize); }
protected override void WriteContent() { DataTable linesTable = DataTableHelper.SelectDistinct(_table, "產線"); //建立寫入前置作業 int writeRow = 4; PasteDataRowsOptions options = new PasteDataRowsOptions(); options.IncludeSummary = true; options.SummaryColumns.AddRange(new string[] { "退驗數量", "待驗數量", "數量", "標準工時", "單位人工成本", "總標準工時", "內部工時", "內部工資", "外包工資", "外包工時", "已生產數量", "尚需工時" }); //對每個產線 foreach (DataRow lineRow in linesTable.Rows) { DataRow[] rows = _table.Select("產線 = '" + lineRow["產線"] + "'", "工作單號,序號"); //寫入內容 options.Row = writeRow; options.SummaryPrefix = lineRow["產線"] + "產線小計"; writeRow = this.SheetAdapter.PasteDataRows(rows, options); } //寫入總計 DataTable tmpTable = _table.Clone(); DataRow totalRow = tmpTable.NewRow(); totalRow[0] = "總計"; foreach (string sumCol in options.SummaryColumns) { if (!string.IsNullOrEmpty(tmpTable.Columns[sumCol].Expression)) { tmpTable.Columns[sumCol].Expression = string.Empty; } object o; o = _table.Compute("SUM(" + sumCol + ")", "產線<>'F'"); totalRow[sumCol] = Convert.IsDBNull(o) ? 0 : (decimal)o; } tmpTable.Rows.Add(totalRow); writeRow = this.SheetAdapter.PasteDataRow(totalRow, writeRow, 1); base.WriteContent(); }
public static void SetFillCode(DevExpress.XtraEditors.LookUpEdit lookup, System.Data.DataTable dtSource, string DisplayMember, string ValueMember, CaptoinStyle style, int AutoSearchColumnIndex) { try { DataTable dt = dtSource.Clone(); DataRow r = dt.NewRow(); if (style == CaptoinStyle.NullString) { r[ValueMember] = ""; r[DisplayMember] = ""; dt.Rows.Add(r); } else if (style == CaptoinStyle.SelectText) { r[ValueMember] = ""; r[DisplayMember] = "선택하세요"; dt.Rows.Add(r); } dt.Load(dtSource.CreateDataReader()); lookup.Properties.SearchMode = DevExpress.XtraEditors.Controls.SearchMode.AutoComplete; lookup.Properties.DataSource = dt; lookup.Properties.DisplayMember = DisplayMember; lookup.Properties.ValueMember = ValueMember; lookup.Properties.AutoSearchColumnIndex = AutoSearchColumnIndex; if (dt.Rows.Count > 0) { lookup.EditValue = dt.Rows[0][ValueMember].ToString(); } } catch (Exception ex) { throw ex; } }
public override void fillRowsToOtherDataset(System.Data.DataTable table, System.Collections.ArrayList rows, System.Data.DataSet data, System.Data.IDbTransaction tran) { int contador = 0; StringBuilder s = new StringBuilder(); data.Tables.Add(table.Clone()); string baseSelectCommand = SqlSyntax.CreateSelectCommandText(table, "WHERE {0}", DBAbstractDataLayer.DataAccessRules.Syntax.DataDeletionStatus.All); using (SqlDataAdapter da = new SqlDataAdapter(new SqlCommand("", (SqlConnection)tran.Connection, (SqlTransaction)tran))) { // por cada linha da tabela modified ou deleted (as marcadas como added nao estao sujeitas a conflitos de concorrencia foreach (DataRow dr in rows) { contador++; s.Append("("); s.Append(buildFilter(table, dr).ToString()); s.Append(")"); // impedir que na query entre 1 "or" a mais if (contador % 200 != 0 && contador < rows.Count) { s.Append(" OR "); } // se ja tiverem sido obtidos 200 IDs, completar a query e executa-la e na base de dados if (contador % 200 == 0 || contador == rows.Count) { // executar comando sql obtido try { //System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(new System.Data.SqlClient.SqlCommand("", (System.Data.SqlClient.SqlConnection) tran.Connection, (System.Data.SqlClient.SqlTransaction) tran)); //da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommand(table, string.Format("where {0}", s), DBAbstractDataLayer.DataAccessRules.SqlClient.SqlSyntax.DataDeletionStatus.All); da.SelectCommand.CommandText = string.Format(baseSelectCommand, s); da.Fill(data, table.TableName); // limpar filtro para o voltar a encher com os proximos 50 s = new System.Text.StringBuilder(); } catch (Exception ex) { Trace.WriteLine(string.Format("Erro ({0}): {1}", table.TableName, ex)); throw; } } } } }
/// <summary> /// 将两个列不同的DataTable合并成一个新的DataTable /// </summary> /// <param name="dt1">表1</param> /// <param name="dt2">表2</param> /// <param name="DTName">合并后新的表名</param> /// <returns></returns> public static System.Data.DataTable UniteDataTable(System.Data.DataTable dt1, System.Data.DataTable dt2, string DTName) { System.Data.DataTable dt3 = dt1.Clone(); for (int i = 0; i < dt2.Columns.Count; i++) { dt3.Columns.Add(dt2.Columns[i].ColumnName); } object[] obj = new object[dt3.Columns.Count]; for (int i = 0; i < dt1.Rows.Count; i++) { dt1.Rows[i].ItemArray.CopyTo(obj, 0); dt3.Rows.Add(obj); } if (dt1.Rows.Count >= dt2.Rows.Count) { for (int i = 0; i < dt2.Rows.Count; i++) { for (int j = 0; j < dt2.Columns.Count; j++) { dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString(); } } } else { DataRow dr3; for (int i = 0; i < dt2.Rows.Count - dt1.Rows.Count; i++) { dr3 = dt3.NewRow(); dt3.Rows.Add(dr3); } for (int i = 0; i < dt2.Rows.Count; i++) { for (int j = 0; j < dt2.Columns.Count; j++) { dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString(); } } } dt3.TableName = DTName; //设置DT的名字 return(dt3); }
private bool obtieneDatosDeProducto() { if ((textBoxClave.Text == "") || (textBoxClave.Text == null)) { MessageBox.Show("Introduce una clave de producto"); return(false); } try { System.Data.DataTable foundRowsTable = new System.Data.DataTable(); DataRow[] foundRows; foundRowsTable = new System.Data.DataTable(); foundRowsTable = tablaEspecificaciones.Clone(); foundRows = tablaEspecificaciones.Select("clave like " + "'" + textBoxClave.Text + "' AND clave not like '%OBSOLETO%'"); foreach (DataRow row in foundRows) { foundRowsTable.ImportRow(row); } if (foundRowsTable.Rows.Count == 1) { textBoxClave.Text = foundRowsTable.Rows[0]["clave"].ToString(); textBoxCliente.Text = foundRowsTable.Rows[0]["cliente"].ToString(); textBoxCalibre.Text = foundRowsTable.Rows[0]["calibre"].ToString(); textBoxMaterial.Text = foundRowsTable.Rows[0]["material"].ToString(); textBoxColor.Text = foundRowsTable.Rows[0]["color"].ToString(); textBoxPerfil.Text = foundRowsTable.Rows[0]["perfil"].ToString(); textBoxCorte.Text = foundRowsTable.Rows[0]["corte"].ToString(); return(true); } else { MessageBox.Show("Clave no encontrada"); return(false); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } }
public System.Data.DataTable GetData(string pSheetName) { int eachRow = 50000; System.Data.DataTable dt = null; ws = wb.Worksheets[pSheetName]; Range rngBegin, rngEnd, rngCell; int colNum = ws.UsedRange.CurrentRegion.Columns.Count; int rowNum = ws.UsedRange.CurrentRegion.Rows.Count; int beginRow = 1; for (int endRow = 0; endRow < rowNum;) { endRow = (endRow + eachRow) > rowNum ? rowNum : (endRow + eachRow); rngBegin = ws.Cells[beginRow, 1]; rngEnd = ws.Cells[endRow, colNum]; rngCell = ws.Range[rngBegin, rngEnd]; object[,] obj = (object[, ])rngCell.Value; if (dt == null) { dt = ObjectHelper.ObjectToDataTable(obj); } else { System.Data.DataTable tempDT = dt.Clone(); tempDT = ObjectHelper.ObjectToDataTable(obj, false, tempDT); foreach (DataRow item in tempDT.Rows) { dt.ImportRow(item); } } Marshal.FinalReleaseComObject(rngBegin); Marshal.FinalReleaseComObject(rngEnd); Marshal.FinalReleaseComObject(rngCell); beginRow = beginRow + eachRow; } return(dt); }
public FrmPatientSelect(string keywordOfName) { InitializeComponent( ); this.Text = "请选择病人"; tbPatientList = HIS.MZ_BLL.OutPatient.GetPatientList("PatName<>'' AND PatName like '%" + keywordOfName + "%' fetch first 100 rows only"); DataTable tbTmp = tbPatientList.Clone( ); foreach (DataColumn col in tbTmp.Columns) { if (col.ColumnName.ToUpper( ) == "PATLISTID" || col.ColumnName.ToUpper( ) == "PATID" || col.ColumnName.ToUpper() == "PATNAME" || col.ColumnName.ToUpper() == "PATSEX" || col.ColumnName.ToUpper() == "CUREDATE" || col.ColumnName.ToUpper() == "PYM" || col.ColumnName.ToUpper() == "WBM" || col.ColumnName.ToUpper() == "VISITNO") { continue; } else { tbPatientList.Columns.Remove(col.ColumnName); } } }
private System.Data.DataTable SortDataTable(System.Data.DataTable DataTableToSort, string ColumnNameToSort) { // Make the DataView we will use and apply the table to be sorted System.Data.DataView dvTemp = new System.Data.DataView(DataTableToSort); // Set the Column to be sorted by dvTemp.Sort = ColumnNameToSort; // Create and setup the table we will use to return the data System.Data.DataTable NewDataTable = DataTableToSort.Clone(); // Loop through all the rows in the data view and add each to the new table for (int i = 0; dvTemp.Count > i; i++) { NewDataTable.Rows.Add(dvTemp[i].Row.ItemArray); } // Return the new table return(NewDataTable); }
private void Bind_Filter_data() { DataView dtsearch = new DataView(dtselect); // DataView dtsearch = new DataView(dt_Search); var search = txt_State_County.Text.ToString(); dtsearch.RowFilter = "State like '%" + search.ToString() + "%' or County like '%" + search.ToString() + "%' "; dt = dtsearch.ToTable(); System.Data.DataTable temptable = dt.Clone(); int startindex = currentpageindex * pagesize; int endindex = currentpageindex * pagesize + pagesize; if (endindex > dt.Rows.Count) { endindex = dt.Rows.Count; } for (int i = startindex; i < endindex; i++) { DataRow row = temptable.NewRow(); Get_Row_Table_Search(ref row, dt.Rows[i]); temptable.Rows.Add(row); } if (temptable.Rows.Count > 0) { gridstate.Rows.Clear(); for (int i = 0; i < temptable.Rows.Count; i++) { gridstate.Rows.Add(); gridstate.Rows[i].Cells[0].Value = i + 1; gridstate.Rows[i].Cells[1].Value = temptable.Rows[i]["State"].ToString(); gridstate.Rows[i].Cells[2].Value = temptable.Rows[i]["County"].ToString(); gridstate.Rows[i].Cells[3].Value = temptable.Rows[i]["Vendor_Id"].ToString(); gridstate.Rows[i].Cells[4].Value = temptable.Rows[i]["Vendor_State_Id"].ToString(); } } lbl_Total_State_County.Text = dt.Rows.Count.ToString(); lblRecordsStatus.Text = (currentpageindex + 1) + " / " + (int)Math.Ceiling(Convert.ToDecimal(dt.Rows.Count) / pagesize); }
/// <summary> /// Séparer les tables avec une colones clef /// </summary> /// <param name="ret"></param> /// <param name="ColKey"></param> /// <returns></returns> public static Dictionary <string, System.Data.DataTable> DataTableSplitByKey(this System.Data.DataTable ret, string ColKey) { Dictionary <string, System.Data.DataTable> retour = new Dictionary <string, System.Data.DataTable>(); foreach (System.Data.DataRow row in ret.Rows) { System.Data.DataTable rtable = null; string ckey = GetRowString(row, ColKey); if (!retour.ContainsKey(ckey)) { rtable = ret.Clone(); retour.Add(ckey, rtable); } else { rtable = retour[ckey]; } rtable.Rows.Add(row.ItemArray); } return(retour); }
private DataTable specialDataSort(DataTable dt) { DataTable sortedDt = dt.Clone(); string Fac = null; dt.AcceptChanges(); foreach (DataRow row in dt.Rows) { if (row.RowState != DataRowState.Deleted) { string newFac = row[dalMac.MacLocation].ToString(); if (Fac != newFac) { foreach (DataRow row2 in dt.Rows) { if (row2.RowState != DataRowState.Deleted) { string FacSearch = row2[dalMac.MacLocation].ToString(); if (Fac == FacSearch) { DataRow newRow2 = sortedDt.NewRow(); newRow2 = row2; sortedDt.ImportRow(newRow2); row2.Delete(); } } } } DataRow newRow = sortedDt.NewRow(); newRow = row; sortedDt.ImportRow(newRow); row.Delete(); Fac = newFac; } } return(sortedDt); }