Merge() public method

public Merge ( DataTable table ) : void
table DataTable
return void
Example #1
0
        public void FormatDataGridView()
        {
            DataTable dt = new DataTable();


            dt = NewDataTable(applicationFileName, ",", true);
            if (applicationFileName.Contains("OPS"))
            {
                dataGridView2.DataSource = dt.Copy();
                dtAll.Merge(dt);
            }
            else if (applicationFileName.Contains("DPM"))
            {
                dataGridView1.DataSource = dt.Copy();
                dtAll.Merge(dt);
            }
            else if (applicationFileName.Contains("BDW"))
            {
                dataGridView3.DataSource = dt.Copy();
                dtAll.Merge(dt);
            }
            else if (applicationFileName.Contains("DEALS"))
            {
                dataGridView4.DataSource = dt.Copy();
                dtAll.Merge(dt);
            }
        }
        public DataTable GetAllDatabaseData()
        {
            Dictionary<string, string> tabs = new Dictionary<string, string>()
            {
                {"Websites Loaded", "webpage_log"},
                {"Websites Actions", "webpage_actions"},
                {"OSIRT Actions", "osirt_actions" },
                {"Attachments", "attachments" },
                {"Videos", "videos" },
            };
            DataTable merged = new DataTable();
            foreach (string table in tabs.Values)
            {
                string columns = DatabaseTableHelper.GetTableColumns(table);
                DataTable data = GetRowsFromColumns(table: table, columns: columns);
                merged.Merge(data, true, MissingSchemaAction.Add);
            }

            DataTable dt = new DatabaseHandler().GetRowsFromColumns("case_notes", "", "date", "time", "note");
            merged.Merge(dt, true, MissingSchemaAction.Add);

            merged.TableName = "merged";
            DataView view = new DataView(merged);
            view.Sort = "date asc, time asc";
            DataTable sortedTable = view.ToTable();
            return sortedTable;
        }
Example #3
0
        public void ProcessRequest(HttpContext context)
        {
            DataSet ds = new DataSet();

            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;

            object[] ob = new object[5];
            ob[0] = context.Request["iMode"];
            ob[1] = Convert.ToDateTime(funDatetime(Convert.ToString(context.Request["StartDate"])));
               // ob[1] = Convert.ToDateTime(context.Request["StartDate"]);
            ob[2] = Convert.ToDateTime(funDatetime(Convert.ToString(context.Request["EndDate"])));
              //  ob[2] = Convert.ToDateTime(context.Request["EndDate"]);
            ob[3] = Convert.ToInt32(context.Request["CompanyID"]);
            ob[4] = Convert.ToInt32(context.Request["BranchID"]);

            ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "[spu_ReportChart]", ob);
            if (ds.Tables.Count > 1)
            {
                DataTable dt = new DataTable();
                dt.Merge(ds.Tables[0]);
                dt.Merge(ds.Tables[1]);
                context.Response.Write(Json.GetJson(dt));
            }
            else
            {
                if (ds.Tables.Count > 0)
                {
                    context.Response.Write(Json.GetJson(ds.Tables[0]));
                }
            }
        }
Example #4
0
        public static void Main(string[] args)
        {
            // jsc needs to see args to make Main into main for javac..


            // see also>
            // X:\jsc.svn\examples\javascript\android\AndroidBroadcastLogger\AndroidBroadcastLogger\ApplicationWebService.cs

            System.Console.WriteLine(
               typeof(object).AssemblyQualifiedName
            );

            //            java.lang.Object, rt
            //'JVMCLRDataTableMerge.exe' (CLR v4.0.30319: JVMCLRDataTableMerge.exe): Loaded 'X:\jsc.svn\examples\java\JVMCLRDataTableMerge\JVMCLRDataTableMerge\bin\Release\JVMCLRDataTableMerge.exports'. Module was built without symbols.
            //The program '[12004] JVMCLRDataTableMerge.exe' has exited with code 0 (0x0).
            //System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089   

            Console.WriteLine("ApplicationWebService cctor");

            var o0 = ScriptedNotifications0.GetDataTable();
            var o1 = ScriptedNotifications.GetDataTable();

            var merge = new DataTable();

            merge.Merge(o0);
            merge.Merge(o1);

            Console.WriteLine("ApplicationWebService cctor done");

            CLRProgram.CLRMain();
        }
Example #5
0
        private void Account()//统计信息
        {
            string sql = "select DEP_NAME,ST_DEPID,count(DEP_NAME) as ST_TOTAL from View_TBDS_STAFFINFO where " + StrWhere() + " group by DEP_NAME,ST_DEPID order by ST_DEPID";

            rep_TJ1.DataSource = DBCallCommon.GetDTUsingSqlText(sql);
            rep_TJ1.DataBind();
            string totalNum = DBCallCommon.GetDTUsingSqlText("select count(*) from View_TBDS_STAFFINFO where " + StrWhere()).Rows[0][0].ToString();

            lb_Total.Text      = totalNum;
            sql                = "select ST_XUELINM ,count(ST_XUELINM) as ST_NUM,'" + totalNum + "' as ST_TOTAL from View_TBDS_STAFFINFO where  " + StrWhere() + " group by ST_XUELINM,ST_XUELI order by cast(ST_XUELI as int) desc";
            rep_TJ2.DataSource = DBCallCommon.GetDTUsingSqlText(sql);
            rep_TJ2.DataBind();
            lb_Total1.Text = totalNum;
            lb_Prop1.Text  = string.Format("{0:f2}", float.Parse(lb_Total1.Text) / float.Parse(lb_Total.Text) * 100).ToString() + "%";

            sql = "select case when ST_ZHICHDJ='5' then '正高级职称' when  ST_ZHICHDJ='4' then '副高级职称'  when   ST_ZHICHDJ='2' then '中级职称' when  ST_ZHICHDJ='1' then '初级职称' else '' end as ST_ZHICHNM,ST_ZHICHDJ,count(ST_ZHICHDJ) as ST_NUM,'" + totalNum + "' as ST_TOTAL from View_TBDS_STAFFINFO where ST_ZHICHDJ!=''  and ST_ZHICHDJ is not null and " + StrWhere() + " group by ST_ZHICHDJ order by ST_ZHICHDJ desc";
            System.Data.DataTable dtZC = DBCallCommon.GetDTUsingSqlText(sql);
            sql = "select case when ST_ZHIJIDJ='5' then '高级技师' when  ST_ZHIJIDJ='4' then '技师'  when  ST_ZHIJIDJ='3' then '高级技能' when   ST_ZHIJIDJ='2' then '中级技能' when  ST_ZHIJIDJ='1' then '初级技能' else '' end as ST_ZHICHNM, ST_ZHIJIDJ as ST_ZHICHDJ,count(ST_ZHIJIDJ) as ST_NUM,'" + totalNum + "' as ST_TOTAL  from View_TBDS_STAFFINFO where ST_ZHIJIDJ!=''  and ST_ZHIJIDJ is not null and " + StrWhere() + "  group by ST_ZHIJIDJ order by  ST_ZHIJIDJ desc";
            System.Data.DataTable dtZJ = DBCallCommon.GetDTUsingSqlText(sql);
            sql = "select '无' as ST_ZHICHNM,count(*) as ST_NUM,'" + totalNum + "' as ST_TOTAL  from View_TBDS_STAFFINFO where (ST_ZHIJIDJ='' or ST_ZHIJIDJ is null) and (ST_ZHICHDJ='' or ST_ZHICHDJ is null) and " + StrWhere();
            System.Data.DataTable dtWU = DBCallCommon.GetDTUsingSqlText(sql);
            dtZC.Merge(dtZJ);
            dtZC.Merge(dtWU);
            rep_TJ3.DataSource = dtZC;
            rep_TJ3.DataBind();
            lb_Total2.Text = totalNum;
            lb_Prop2.Text  = string.Format("{0:f2}", float.Parse(lb_Total2.Text) / float.Parse(lb_Total.Text) * 100).ToString() + "%";

            sql = "SELECT ST_AREA, ST_NUM,(SELECT  COUNT(*)  FROM  dbo.View_TBDS_STAFFINFO where " + StrWhere() + ") AS ST_TOTAL FROM  ( SELECT     '55<=X' AS ST_AREA, COUNT(*) AS ST_NUM FROM dbo.View_TBDS_STAFFINFO  WHERE  (ST_AGE >= 55 and " + StrWhere() + ") UNION ALL SELECT  '45<=X<55' AS ST_AREA, COUNT(*) AS ST_NUM FROM   dbo.View_TBDS_STAFFINFO  WHERE  (ST_AGE >= 45 AND ST_AGE< 55 and " + StrWhere() + ") UNION ALL  SELECT  '35<=X<45' AS ST_AREA, COUNT(*) AS ST_NUM  FROM   dbo.View_TBDS_STAFFINFO  WHERE (ST_AGE >= 35 AND ST_AGE< 45 and  " + StrWhere() + ") UNION ALL SELECT     '25<=X<35' AS ST_AREA, COUNT(*) AS ST_NUM  FROM   dbo.View_TBDS_STAFFINFO  WHERE   (ST_AGE >= 25 AND ST_AGE< 35  and " + StrWhere() + ") UNION ALL SELECT   'X<25' AS ST_AREA, COUNT(*) AS ST_NUM FROM dbo.View_TBDS_STAFFINFO  WHERE  (ST_AGE < 25 and " + StrWhere() + ") ) AS derivedtbl_1";
            rep_TJ4.DataSource = DBCallCommon.GetDTUsingSqlText(sql);
            rep_TJ4.DataBind();
            lb_Total3.Text = totalNum;
            lb_Prop3.Text  = string.Format("{0:f2}", float.Parse(lb_Total3.Text) / float.Parse(lb_Total.Text) * 100).ToString() + "%";

            sql = "select ST_GENDER,count(ST_GENDER) as ST_NUM from View_TBDS_STAFFINFO where " + StrWhere() + " group by ST_GENDER";
            rep_TJ5.DataSource = DBCallCommon.GetDTUsingSqlText(sql);
            rep_TJ5.DataBind();
            lb_Total4.Text     = totalNum;
            sql                = "select ST_SEQUEN,count(ST_SEQUEN) as ST_NUM,'" + totalNum + "' as ST_TOTAL  from (select case when ST_SEQUEN is null or ST_SEQUEN='' then '其他' else ST_SEQUEN end as ST_SEQUEN from View_TBDS_STAFFINFO where " + StrWhere() + ")a group by ST_SEQUEN";
            rep_TJ6.DataSource = DBCallCommon.GetDTUsingSqlText(sql);
            rep_TJ6.DataBind();
            lb_Total5.Text = totalNum;
            lb_Prop5.Text  = string.Format("{0:f2}", float.Parse(lb_Total5.Text) / float.Parse(lb_Total.Text) * 100).ToString() + "%";

            sql = "select ST_CONTR,count(ST_CONTR) as ST_NUM,'" + totalNum + "' as ST_TOTAL  from (select case when ST_CONTR is null or ST_CONTR='' then ' 其他' else ST_CONTR end as ST_CONTR from View_TBDS_STAFFINFO where  " + StrWhere() + ")a group by ST_CONTR order by ST_CONTR desc";
            rep_TJ7.DataSource = DBCallCommon.GetDTUsingSqlText(sql);
            rep_TJ7.DataBind();
            lb_Total6.Text = totalNum;
            lb_Prop6.Text  = string.Format("{0:f2}", float.Parse(lb_Total6.Text) / float.Parse(lb_Total.Text) * 100).ToString() + "%";

            //离职信息
            sql = "select LZ_BUMEN,LZ_BUMENID ,count(LZ_PERSON) as RS,(select count(LZ_ID) from OM_LIZHISHOUXU where LZ_SPZT='y') as ZS from OM_LIZHISHOUXU where LZ_SPZT='y' group by LZ_BUMENID,LZ_BUMEN";
            rptLZXX.DataSource = DBCallCommon.GetDTUsingSqlText(sql);
            rptLZXX.DataBind();
            sql = "select count(LZ_ID) from  OM_LIZHISHOUXU where LZ_SPZT='y'";
            System.Data.DataTable dtLZ = DBCallCommon.GetDTUsingSqlText(sql);
            lbLZHJ.Text = dtLZ.Rows[0][0].ToString();
        }
        public DataTable VerFachada1()
        {
            oTabla = oAgente.ListarAgente();
            oTabla2 = oCliente.ListarCliente();
            oTabla3 = oPunto.ListarPuntoVenta();

            oTabla.Merge(oCliente.ListarCliente());
            oTabla.Merge(oPunto.ListarPuntoVenta());

            return oTabla;
        }
Example #7
0
 /// <summary>
 /// Obtiene todas las reservaciones hechas en el sistema
 /// </summary>
 /// <returns>DataTable Object (start,end,name,id)</returns>
 public DataTable ObtenerReservaciones()
 {
     DataTable toReturn = new DataTable();
     toReturn.Columns.Add("start", typeof(DateTime));
     toReturn.Columns.Add("end", typeof(DateTime));
     toReturn.Columns.Add("name", typeof(string));
     toReturn.Columns.Add("id", typeof(string));
     toReturn.Merge(ObtenerEventos());
     toReturn.Merge(ObtenerCursos());
     toReturn.Merge(ObtenerAprobaciones());
     return toReturn;
 }
        private void btnDown_Click(object sender, EventArgs e)
        {
            grdView.MoveNextPage();
            int topRowIndex = grdView.TopRowIndex;

            if ((grdView.IsLastRow) && (grdView.RowCount > 0))
            {
                System.Data.DataRow Row = grdView.GetDataRow(grdView.GetSelectedRows()[0]);
                string lastItemName     = Row["INVENTSERIALID"].ToString();
                itemTable.Merge(GetItemList(lastItemName, txtKeyboardInput.Text, getHowManyRows));
                grdView.TopRowIndex = topRowIndex;
            }

            txtKeyboardInput.Select();
        }
        public async void TableDataIsEqual(OBData.DataTable dt1, OBData.DataTable dt2, string schema)
        {
            _engine         = new AutomationEngineInstance(null);
            _mergeDataTable = new MergeDataTableCommand();

            VariableMethods.CreateTestVariable(dt1, _engine, "dt1", typeof(OBData.DataTable));
            VariableMethods.CreateTestVariable(dt2, _engine, "dt2", typeof(OBData.DataTable));

            switch (schema)
            {
            case "Add":
                dt2.Merge(dt1, false, MissingSchemaAction.Add);
                break;

            case "AddWithKey":
                dt2.Merge(dt1, false, MissingSchemaAction.AddWithKey);
                break;

            case "Error":
                dt2.Merge(dt1, false, MissingSchemaAction.Error);
                break;

            case "Ignore":
                dt2.Merge(dt1, false, MissingSchemaAction.Ignore);
                break;

            default:
                throw new NotImplementedException("Test for schema '" + schema + "' not implemented");
            }

            _mergeDataTable.v_SourceDataTable      = "{dt1}";
            _mergeDataTable.v_DestinationDataTable = "{dt2}";
            _mergeDataTable.v_MissingSchemaAction  = schema;

            _mergeDataTable.RunCommand(_engine);

            OBData.DataTable resultDataTable = (OBData.DataTable) await _mergeDataTable.v_DestinationDataTable.EvaluateCode(_engine);

            Assert.Equal(dt2.GetType(), resultDataTable.GetType());
            // Check each row / column pair and assert equivalence
            for (int row = 0; row < dt2.Rows.Count; row++)
            {
                for (int col = 0; col < dt2.Columns.Count; col++)
                {
                    Assert.Equal(dt2.Rows[row][dt2.Columns[col]], resultDataTable.Rows[row][resultDataTable.Columns[col]]);
                }
            }
        }
Example #10
0
        public void ProcessRequest(HttpContext context)
        {
            DataSet ds = new DataSet();
            string mode = context.Request["handler_mode"];
            if (mode == "print")
            {
                object[] ob = new object[2];
                ob[0] = Convert.ToInt32(context.Request["pid"]);
                ob[1] = context.Request["imode"];
                ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "spu_InvoicePrint", ob);
            }
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables.Count > 1)
                {
                    DataTable dt = new DataTable();
                    for (var i = 0; i < ds.Tables.Count; i++)
                    {
                        dt.Merge(ds.Tables[i]);
                    }
                    context.Response.Write(Json.GetJson(dt));
                }
                else
                {
                    context.Response.Write(Json.GetJson(ds.Tables[0]));
                }

            }
        }
Example #11
0
        /// <summary>
        /// Obtiene todas las reservaciones hechas por la aprobacion de una solicitud
        /// </summary>
        /// <returns>DataTable Object (start,end,name,id)</returns>
        private DataTable ObtenerAprobaciones()
        {
            cUDGDFAPROBACIONNegocios cAprobaciones = new cUDGDFAPROBACIONNegocios(0, "", 0, "");
            DataTable dtAprobaciones = cAprobaciones.Seleccionar_Todo_Detallado();
            DataTable toReturn = new DataTable();
            toReturn.Columns.Add("start", typeof(DateTime));
            toReturn.Columns.Add("end", typeof(DateTime));
            toReturn.Columns.Add("name", typeof(string));
            toReturn.Columns.Add("id", typeof(string));
            String sFechainicio, sFechafin, sHorainicio, sHorafin, sDescripcion;
            String sID;
            Boolean blunes, bmartes, bmiercoles, bjueves, bviernes, bsabado, bdomingo;

            foreach (DataRow drLocalRow in dtAprobaciones.Rows)
            {
                sFechainicio = drLocalRow[1].ToString();
                sFechafin = drLocalRow[2].ToString();
                sHorainicio = drLocalRow[3].ToString();
                sHorafin = drLocalRow[4].ToString();
                sDescripcion = "Reservacion de " + drLocalRow[5].ToString();
                sID = "Reservacion:" + int.Parse(drLocalRow[0].ToString());
                blunes = true;
                bmartes = true;
                bmiercoles = true;
                bjueves = true;
                bviernes = true;
                bsabado = true;
                bdomingo = true;
                toReturn.Merge(ObtenerFechas(sFechainicio, sFechafin, sHorainicio, sHorafin, sDescripcion, sID, blunes, bmartes, bmiercoles, bjueves, bviernes, bsabado, bdomingo));
            }

            return toReturn;
        }
Example #12
0
        protected void ddlCourses_SelectedIndexChanged(object sender, EventArgs e)
        {
            int courseID = int.Parse(ddlCourses.SelectedValue);
            Course course = (Course.GetCourse(courseID)).ElementAt(0);
            IEnumerable<Session> sessions = Classes.Session.GetSessionsByCourseID(courseID);
            //IEnumerable<ClientSession> clientSessions = (ClientSession.GetClientSessionsByClientID(clientID));
            DataTable sessionsTable = new DataTable("SessionsTable");
            foreach (Session sesh in sessions)
            {
                using (DatabaseConnection db = new DatabaseConnection("dbo.GetSession"))
                {
                    // Set Parameters
                    db.comm.Parameters.AddWithValue("SessionID", sesh.SessionID);

                    // Open Connection
                    db.conn.Open();

                    // Execute Command
                    SqlDataAdapter MyAdapter = new SqlDataAdapter();
                    MyAdapter.SelectCommand = db.comm;
                    DataTable table = new DataTable();

                    // Read Response
                    MyAdapter.Fill(table);

                    sessionsTable.Merge(table);
                    db.Dispose();
                }
            }
            modSessionTable(sessionsTable);
            //gvSessions.DataSource = sessionsTable.DefaultView;
            //gvSessions.DataBind();
        }
Example #13
0
        public static string displayNPTMetricsX(List<string> _arr)
        {
            DataTable dummy = new DataTable();
            dummy.Columns.Add("TaskName");
            dummy.Columns.Add("Start");
            dummy.Columns.Add("End");
            dummy.Columns.Add("Elapsed");

            SystemObjects.OPT _opt = new SystemObjects.OPT();
            _opt.WorkdayID = Convert.ToInt32(_arr[0]);
            DataSet ds = new DataSet();
            try
            {
                dummy.Merge(_opt.DisplayNPTMetricsX());
                if (dummy.Rows.Count < 1)
                {
                    dummy.Rows.Add();
                }
                ds.Tables.Add(dummy);
            }
            catch (Exception ex)
            {

            }
            return ds.GetXml();
        }
Example #14
0
 //查询窗口添加数据调用
 public void LoadDataByVin(DataView vins)
 {
     try
     {
         if (vins != null && vins.Table.Rows.Count > 0)
         {
             System.Data.DataTable dt = (System.Data.DataTable)gridControl1.DataSource;
             if (dt != null)
             {
                 dt.Merge(vins.Table);
                 string[] strComuns = { "VIN", "CLXH", "TYMC", "RLLX", "CT_ZHGKRLXHL", "ZCZBZL", "CT_BSQXS", "ZWPS", "UPDATEFIELD", "FIELDOLD", "FIELDNEW", "APPLYTYPE" };
                 dt = dt.AsDataView().ToTable(true, strComuns);
                 gridControl1.DataSource = dt;
             }
             else
             {
                 gridControl1.DataSource = vins.ToTable();
             }
             System.Data.DataView dv = ((System.Data.DataTable)gridControl1.DataSource).AsDataView();
             var insert_o            = dv.ToTable(true, "VIN", "APPLYTYPE").Select("APPLYTYPE='补传'");
             var update = dv.ToTable(true, "VIN", "APPLYTYPE").Select("APPLYTYPE='修改'");
             var delete = dv.ToTable(true, "VIN", "APPLYTYPE").Select("APPLYTYPE='撤销'");
             INSERT_O_SL.Text = insert_o.Length.ToString();
             UPDATE_SL.Text   = update.Length.ToString();
             DELETE_SL.Text   = delete.Length.ToString();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #15
0
        // récupère toutes les valeurs d'une table donnée
        // renvoie un Dataset
        public static DataSet GetAllRecords(string lobSystemInstance, string entityName)
        {
            DataSet ds = new DataSet(entityName);

            NamedLobSystemInstanceDictionary sysInstances = ApplicationRegistry.GetLobSystemInstances();
            LobSystemInstance instance = sysInstances[lobSystemInstance];
            Entity entity = instance.GetEntities()[entityName];

            // Get the finder method
            MethodInstance finder = entity.GetFinderMethodInstance();

            //Execute Finder method
            DbEntityInstanceEnumerator records = (DbEntityInstanceEnumerator)entity.Execute(finder, instance);

            //Load matching entities into a DataTable
            DataTable entitiesTable = new DataTable();
            while (records.MoveNext())
            {
                //Load each entity and include the Action URL
                DbEntityInstance record = (DbEntityInstance)records.Current;
                DataTable entityTable = record.EntityAsDataTable;
                entityTable.AcceptChanges();
                entitiesTable.Merge(entityTable);
            }

            //DataTable ordersTable = customerOrders.Tables.Add(“Orders”);
            ds.Tables.Add(entitiesTable);
            return ds;
        }
Example #16
0
        // Permet d'éxecuter une méthode select donné avec des paramètres
        // renvoie un Dataset
        public static DataSet GetAllRecordsWithParam(string lobSystemInstance, string entityName, string methodInstance, object[] parameters)
        {
            DataSet ds = new DataSet(entityName);

            NamedLobSystemInstanceDictionary sysInstances = ApplicationRegistry.GetLobSystemInstances();
            LobSystemInstance instance = sysInstances[lobSystemInstance];
            Entity entity = instance.GetEntities()[entityName];

            // Get the method
            MethodInstance methInst = entity.GetMethodInstances()[methodInstance];

            //Execute Finder method
            DbEntityInstanceEnumerator records = (DbEntityInstanceEnumerator)entity.Execute(methInst, instance, ref parameters);

            //Load matching entities into a DataTable
            DataTable entitiesTable = new DataTable();
            while (records.MoveNext())
            {
                //Load each entity and include the Action URL
                DbEntityInstance record = (DbEntityInstance)records.Current;
                DataTable entityTable = record.EntityAsDataTable;
                entityTable.AcceptChanges();
                entitiesTable.Merge(entityTable);
            }

            ds.Tables.Add(entitiesTable);
            return ds;
        }
Example #17
0
        private void btnPageDown_Click(object sender, EventArgs e)
        {
            lastActiveDateTime = DateTime.Now;
            grdView.MoveNextPage();
            int topRowIndex = grdView.TopRowIndex;

            if ((grdView.IsLastRow) && (grdView.RowCount > 0))
            {
                overrideTable.Merge(GetOverrideList(loadedCount, txtKeyboardInput.Text, getHowManyRows));
                grdView.TopRowIndex = topRowIndex;
            }


            txtKeyboardInput.Select();
            CheckRowPosition();
        }
        /// <summary>
        /// Processes the result of a data submission to the Server where the result of that operation is
        /// <see cref="TSubmitChangesResult.scrOK" />. (Overload for DataTables.)
        /// </summary>
        /// <param name="ACallingFormOrUserControl"></param>
        /// <param name="ALocalDT"></param>
        /// <param name="ASubmitDT"></param>
        /// <param name="APetraUtilsObject"></param>
        /// <param name="AVerificationResults"></param>
        /// <param name="ASetPrimaryKeyOnlyMethod"></param>
        /// <param name="AMasterDataTableSaveCall"></param>
        /// <param name="ACalledFromUserControl"></param>
        /// <param name="ACallAcceptChangesOnReturnedDataBeforeMerge"></param>
        public static void ProcessSubmitChangesResultOK(IFrmPetra ACallingFormOrUserControl, DataTable ALocalDT,
            DataTable ASubmitDT, TFrmPetraEditUtils APetraUtilsObject, TVerificationResultCollection AVerificationResults,
            Action <bool>ASetPrimaryKeyOnlyMethod, bool AMasterDataTableSaveCall, bool ACalledFromUserControl,
            bool ACallAcceptChangesOnReturnedDataBeforeMerge = false)
        {
            if (AMasterDataTableSaveCall)
            {
                // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server
                ALocalDT.AcceptChanges();

                // Merge back with data from the Server (eg. for getting Sequence values)
                if (ACallAcceptChangesOnReturnedDataBeforeMerge)
                {
                    ASubmitDT.AcceptChanges();
                }

                ALocalDT.Merge(ASubmitDT, false);

                // Need to accept any new modification ID's
                ALocalDT.AcceptChanges();

                if (ASetPrimaryKeyOnlyMethod != null)
                {
                    // Ensure the Primary-Key(s)-containing Controls are disabled to prevent further modification of Primary Key values
                    ASetPrimaryKeyOnlyMethod(true);
                }
            }

            CommonPostMergeOperations(ACallingFormOrUserControl, APetraUtilsObject,
                AVerificationResults, ACalledFromUserControl);
        }
Example #19
0
        public static string displayemployee(List<string> _arr)
        {
            DataTable dummy = new DataTable();
            dummy.Columns.Add("No");
            dummy.Columns.Add("WorkdayID");
            dummy.Columns.Add("Name");

            SystemObjects.HeadCount _hc = new SystemObjects.HeadCount();
            _hc.TeamID = Convert.ToInt32(_arr[0]);
            _hc.Date =  Convert.ToInt32(_arr[1]);
            _hc.Year = Convert.ToInt32(_arr[2]);
            DataSet ds = new DataSet();
            try
            {
                dummy.Merge(_hc.DisplayEmployee());
                if (dummy.Rows.Count < 1)
                {
                    dummy.Rows.Add();
                }
                ds.Tables.Add(dummy);
            }
            catch (Exception ex)
            {

            }
            return ds.GetXml();
        }
Example #20
0
        /// <summary>
        /// Metode for å søke på brukere.
        /// Lager en query basert på valg og søkeord og binder den nye informasjonen til en datatable.
        /// Om resultatet er tomt vil det ikke skje noen forandring.
        /// </summary>
        public void FilterGridView()
        {
            DataTable filterTable = new DataTable(); //Lager en data table for å lagre data fra spørringen

            //Henter alle fra User-tabellen med korrekt kolonnenavn / vilkår fra databasen
            string filterStatement = String.Format("SELECT userID, surname, firstname, username, password, phone, mail, teamName, groupName FROM User, Team, UserGroup WHERE {0} LIKE '%{1}%' AND User.teamID = Team.teamID AND User.groupID = UserGroup.groupID", FilterSearchDropdown.Text, FilterSearchTerms.Text);

            filterTable = db.AdminGetAllUsers(filterStatement);

            //Henter ut brukere som ikke tilhører et team og merger tabellene
            string queryNull = String.Format("SELECT userID, surname, firstname, username, phone, mail, teamID \"teamName\", groupName FROM User, UserGroup WHERE {0} LIKE '%{1}%' AND User.teamID IS NULL  AND User.groupID = UserGroup.groupID", FilterSearchDropdown.Text, FilterSearchTerms.Text);
            tableNull = db.AdminGetAllUsers(queryNull);

            filterTable.Merge(tableNull, true, MissingSchemaAction.Ignore);

            if (filterTable.Rows.Count > 0) //Hvis søkevilkåret gir resultater
            {
                //Om søket ga resultat
                ViewState["table"] = filterTable;
                GridViewAdmin.DataSource = filterTable; //Setter data source til den filtrerte data table
                GridViewAdmin.DataBind();               //Oppdaterer data i GridView
            }
            else
            {
                //Søket ga ingen resultat, trenger ikke refreshe GridViewAdmin
                FilterSearchTerms.Text = "Søket ga ingen resultat!"; //Gir bruker beskjed
            }
        }
Example #21
0
 private void AddTable(System.Data.DataTable tempTable, System.Data.DataTable currentTable)
 {
     if (tempTable.Rows.Count <= 0)
     {
         tempTable.Merge(currentTable, true, MissingSchemaAction.AddWithKey);
     }
     else
     {
         int index = tempTable.Columns.Count;
         for (int j = 0; j < currentTable.Columns.Count; j++)
         {
             DataColumn dataColumn = new DataColumn();
             dataColumn.ColumnName = "F" + (tempTable.Columns.Count + 1);
             dataColumn.Caption    = "F" + (tempTable.Columns.Count + 1);
             tempTable.Columns.Add(dataColumn);
         }
         for (int a = 0; a < tempTable.Rows.Count; a++)
         {
             for (int b = index; b < tempTable.Columns.Count; b++)
             {
                 tempTable.Rows[a][tempTable.Columns[b]] = GetCurrentTable(currentTable, a, b - index);
             }
         }
     }
 }
Example #22
0
        static void Main(string[] args)
        {
            DataSet ds = GetDataSet();
            DataTable full = new DataTable();
            foreach (DataTable table in ds.Tables) 
            {
                full.Merge(table);
            }

            var result = from tab in full.AsEnumerable()
                         group tab by tab["time"]
                             into groupDt
                             select new
                             {
                                 Group = groupDt.Key,
                                 Sum = groupDt.Sum(r => decimal.Parse(r["count"].ToString()))
                             };
            var max = result.OrderByDescending(x => x.Sum).First();
            DateTime maxTime = (DateTime)max.Group;
            CultureInfo ci = CultureInfo.InvariantCulture;

            Console.WriteLine("Максимальное количество посетителей "
                + max.Sum + " было в " + maxTime.ToString("HH:mm:ss", ci));

            Console.ReadKey();
        }
Example #23
0
        public void ProcessRequest(HttpContext context)
        {
            DataSet ds = new DataSet();
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;

            object[] ob = new object[14];

            ob[0] = Convert.ToInt32((context.Request["MilestoneID"] == "" ? "0" : context.Request["MilestoneID"]));
            ob[1] = context.Request["MilestoneName"];
            ob[2] = Convert.ToInt32((context.Request["ProjectID"] == "" ? "0" : context.Request["ProjectID"]));
            ob[3] = Convert.ToDateTime(((context.Request["MilestoneDate"] == null || context.Request["MilestoneDate"] == "") ? "1990/1/1" : context.Request["MilestoneDate"]));
            ob[4] = Convert.ToInt32((context.Request["AssignedTo"] == "" ? "0" : context.Request["AssignedTo"]));
            ob[5] = Convert.ToInt32((context.Request["TypeID"] == "" ? "0" : context.Request["TypeID"]));
            ob[6] = context.Request["Description"];
            ob[7] = Convert.ToInt32((context.Request["CreatedBy"] == "" ? "0" : context.Request["CreatedBy"]));
            ob[8] = Convert.ToDateTime(((context.Request["CreatedOn"] == null || context.Request["CreatedOn"] == "") ? "1990/1/1" : context.Request["CreatedOn"]));
            ob[9] = Convert.ToInt32((context.Request["ModifiedBy"] == "" ? "0" : context.Request["ModifiedBy"]));
            ob[10] = Convert.ToDateTime(((context.Request["ModifiedOn"] == null || context.Request["ModifiedOn"] == "") ? "1990/1/1" : context.Request["ModifiedOn"]));
            ob[11] = Convert.ToInt32((context.Request["CompanyID"] == "" ? "0" : context.Request["CompanyID"]));
            ob[12] = Convert.ToInt32((context.Request["BranchID"] == "" ? "0" : context.Request["BranchID"]));
            ob[13] = context.Request["imode"];

            ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "[spu_Milestone]", ob);
            if (ds.Tables.Count > 0)
            {
                DataTable dt = new DataTable();
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    dt.Merge(ds.Tables[i]);
                }
                context.Response.Write(Json.GetJson(dt));
            }
        }
Example #24
0
        //lấy ra sinh viên tham gia 1 kỳ thi
        public static DataTable GopKetQua1(IList<int> list)
        {
            var table = new DataTable();
            try
            {
                var tb = new DataTable[list.Count];
                var str = new string[list.Count];

                for (var i = 0; i < list.Count; i++)
                {
                    str[i] =
                        "select bl.MaSV,s.HoSV,s.TenSV,s.NgaySinh,l.MaLop, bl.DiemThi as [Diem" + (i + 1) +
                        "], bl.DiemThi as[TongDiem]" +
                        " from BAILAM bl" +
                        " join SINHVIEN s on bl.MaSV = s.MaSV" +
                        " join LOP l on s.IdLop = l.ID" +
                        " where IdKyThi = " + list[i] + " and DiemThi is not null and not exists( select c.MaSV From (" +
                        Getstr1(list) + " ) c where bl.MaSV = c.MaSV)";
                    tb[i] = Conn.GetTable(str[i]);
                    table.Merge(tb[i]);
                }

            }
            catch (Exception ex)
            {
                Log2File.LogExceptionToFile(ex);
            }
            return table;
        }
        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            string InstanceName = TextBoxSource.Text;

            //List Catalogs(DBs)
            string strMDX = "select * from $system.DBSCHEMA_CATALOGS";
            string strConnString = "Datasource=" + InstanceName;

            System.Data.DataTable dtDB = GetDataTable(strConnString, strMDX); //returns data table with DB details

            //Enumerate cubes in each database
            ArrayList DBList = ReturnValueFromDataTable(dtDB, 0); //Get DB Name (Catalog_Name) from data table
            dtDB.Dispose();

            System.Data.DataTable dtCubes = new System.Data.DataTable();
            System.Data.DataTable dtPartial = new System.Data.DataTable();

            foreach (string DBName in DBList)
            {
                strMDX = "SELECT * FROM $system.MDSchema_Cubes WHERE CUBE_SOURCE=1";
                strConnString = "Datasource=" + TextBoxSource.Text + ";Catalog=" + DBName;
                dtPartial = GetDataTable(strConnString, strMDX); //get all Cubes for the DB DBName
                DataColumn CubeLink = dtPartial.Columns.Add("Link"); // Add a column "Link" in the data table
                CubeLink.SetOrdinal(0); //make new column as first column in table

                dtCubes.Merge(dtPartial);
                dtPartial.Dispose();
            }

            GridViewResults.AutoGenerateColumns = true;
            GridViewResults.DataSource = dtCubes; //returns data table with DB details
            GridViewResults.DataBind();
            dtCubes.Dispose();
        }
Example #26
0
        private void GetFromDB(object sender, RoutedEventArgs e)
        {
            // Create an open a connection.
            try
            {
                using (SqlConnection cn = new SqlConnection())
                {
                    cn.ConnectionString = _cnStrBuilder.ConnectionString;
                    cn.Open();
                    string strSQL = "Select  * From Sales.SalesOrderDetail";
                    if (tb.Text != String.Empty)
                    {
                        strSQL = "Select top " + tb.Text + " * From Sales.SalesOrderDetail";
                    }
                    _dataSet = new DataSet();
                    SqlDataAdapter adapter = new SqlDataAdapter(strSQL, cn);
                    // adapter.FillSchema(_dataSet, SchemaType.Mapped);
                    adapter.Fill(_dataSet);
                    tesTable = _dataSet.Tables[0];

                    // return _dataSet.Tables[0];
                    //500000行 翻番
                    for (int i = 0; i < 2; i++)
                    {
                        tesTable.Merge(tesTable.Copy());
                    }
                    dg.ItemsSource = tesTable.DefaultView;
                    tb.Text        = tesTable.Rows.Count.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #27
0
 //导入
 protected void btnInput_Click(object sender, EventArgs e)
 {
     if (txtInputNum.Text == "" || txtInputPihao.Text.ToString() == "")
     {
         //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('提示:请输入导入倍数及源数据');", true);
         Response.Write("<script>alert('提示:请输入导入倍数及源数据');</script>");
     }
     else
     {
         string num = txtInputNum.Text.Trim();
         System.Data.DataTable dt = GetDataFromGrid("import");
         sqlText  = "select  PS_ENGID,PS_TUHAO,PS_NAME,PS_LEVEL,cast(cast(PS_MIANJI as float)*" + num + " as varchar(50)) as PS_MIANJI,PS_BOTMARID,PS_BOTSHAPE,PS_BOTHOUDU,cast(cast(PS_BOTYONGLIANG as float)*" + num + " as varchar(50)) as PS_BOTYONGLIANG,cast(cast(PS_BOTXISHIJI as float)*" + num + " as varchar(50)) as PS_BOTXISHIJI,cast(PS_BOTMWEIGHT as varchar(50)) as PS_BOTMWEIGHT,PS_MIDMARID,PS_MIDSHAPE,PS_MIDHOUDU,cast(cast(PS_MIDYONGLIANG as float)*" + num + " as varchar(50)) as PS_MIDYONGLIANG,cast(cast(PS_MIDXISHIJI as float)*" + num + " as varchar(50)) as PS_MIDXISHIJI,cast(PS_MIDMWEIGHT as varchar(50)) as PS_MIDMWEIGHT,PS_TOPMARID,PS_TOPSHAPE,PS_TOPHOUDU,cast(cast(PS_TOPYONGLIANG as float)*" + num + " as varchar(50)) as PS_TOPYONGLIANG,cast(cast(PS_TOPXISHIJI as float)*" + num + " as varchar(50)) as PS_TOPXISHIJI,cast(PS_TOPMWEIGHT as varchar(50)) as PS_TOPMWEIGHT,PS_TOPCOLOR,PS_TOPCOLORLABEL,PS_TOTALHOUDU,PS_BEIZHU,PS_BGBEIZHU ";
         sqlText += "from View_TM_PAINTSCHEMEDETAIL where PS_PID='" + txtInputPihao.Text + "'";
         try
         {
             DataTable dt1 = DBCallCommon.GetDTUsingSqlText(sqlText);
             dt.Merge(dt1, true);
             for (int i = 0; i < 10; i++)
             {
                 DataRow newRow = dt.NewRow();
                 dt.Rows.Add(newRow);
             }
             this.Repeater1.DataSource = dt;
             this.Repeater1.DataBind();
         }
         catch (Exception)
         {
             //  ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('提示:导入数据有误,存在类型转换错误!');", true);
             Response.Write("<script>alert('提示:导入数据有误,存在类型转换错误!');</script>");
         }
     }
 }
Example #28
0
        public static string displayReARTickets(List<string> _arr)
        {
            DataTable dummy = new DataTable();
            dummy.Columns.Add("TicketNo", typeof(Int64));
            dummy.Columns.Add("ConcernAction", typeof(String));
            dummy.Columns.Add("TicketDescription", typeof(String));
            dummy.Columns.Add("TicketDate", typeof(DateTime));
            dummy.Columns.Add("TicketStatus", typeof(String));
            dummy.Columns.Add("SummaryOfConcern", typeof(String));

            SystemObjects.ReARObj _rearobj = new SystemObjects.ReARObj();
            _rearobj.WorkdayID = Convert.ToInt32(_arr[0].ToString());

            DataSet ds = new DataSet();
            try
            {
                dummy.Merge(_rearobj.displayReAR(Convert.ToBoolean(_arr[1].ToString())));
                if (dummy.Rows.Count < 1)
                {
                    dummy.Rows.Add();
                }
                ds.Tables.Add(dummy);
            }
            catch (Exception ex)
            {

            }
            return ds.GetXml();
        }
Example #29
0
        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            string InstanceName = TextBoxSource.Text;

            //List Catalogs(DBs)
            string strMDX        = "select * from $system.DBSCHEMA_CATALOGS";
            string strConnString = "Datasource=" + InstanceName;

            System.Data.DataTable dtDB = GetDataTable(strConnString, strMDX); //returns data table with DB details

            //Enumerate cubes in each database
            ArrayList DBList = ReturnValueFromDataTable(dtDB, 0); //Get DB Name (Catalog_Name) from data table

            dtDB.Dispose();

            System.Data.DataTable dtCubes   = new System.Data.DataTable();
            System.Data.DataTable dtPartial = new System.Data.DataTable();

            foreach (string DBName in DBList)
            {
                strMDX        = "SELECT * FROM $system.MDSchema_Cubes WHERE CUBE_SOURCE=1";
                strConnString = "Datasource=" + TextBoxSource.Text + ";Catalog=" + DBName;
                dtPartial     = GetDataTable(strConnString, strMDX); //get all Cubes for the DB DBName
                DataColumn CubeLink = dtPartial.Columns.Add("Link"); // Add a column "Link" in the data table
                CubeLink.SetOrdinal(0);                              //make new column as first column in table

                dtCubes.Merge(dtPartial);
                dtPartial.Dispose();
            }

            GridViewResults.AutoGenerateColumns = true;
            GridViewResults.DataSource          = dtCubes; //returns data table with DB details
            GridViewResults.DataBind();
            dtCubes.Dispose();
        }
Example #30
0
        public static string displayNpt(List<string> _arr)
        {
            DataTable dummy = new DataTable();
            dummy.Columns.Add("Task Name");
            dummy.Columns.Add("Status");

            SystemObjects.OPT _opt = new SystemObjects.OPT();

            _opt.TeamID = Convert.ToInt32(_arr[0].ToString());
            DataSet ds = new DataSet();
            try
            {
                dummy.Merge(_opt.DisplayNptTask());
                if (dummy.Rows.Count < 1)
                {
                    dummy.Rows.Add();
                }
                ds.Tables.Add(dummy);
            }
            catch (Exception ex)
            {

            }
            return ds.GetXml();
        }
Example #31
0
        public void renderList(object sender, List <int> ids)
        {
            if (ids.Count > 0)
            {
                allids.AddRange(ids);
                var dtData = ctrl.getByids(ids);
                dtData.Columns.Add("attrvalue");
                List <int> combs = new List <int>();
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    if (dtData.Rows[i]["combination"] != DBNull.Value)
                    {
                        combs.Add(Convert.ToInt32(dtData.Rows[i]["combination"]));
                    }
                }
                dt.Merge(dtData);
                dataGridView1.DataSource = dt;
                Dictionary <int, string> map = sbCtrl.getbyCombIds(combs);
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    if (dataGridView1.Rows[i].Cells["combination"].Value != DBNull.Value)
                    {
                        var comb = Convert.ToInt32(dataGridView1.Rows[i].Cells["combination"].Value);

                        if (map.Keys.Contains(comb))
                        {
                            dataGridView1.Rows[i].Cells["attrvalue"].Value = map[comb];
                        }
                    }
                }
            }
        }
Example #32
0
 //Populate tree node
 public void TreeNodePopulate(TreeNodeCollection nodes, IToken token)
 {
     //Parents nodes
     treeNodes = authorManager.getAllPermission();
     treeNodes.Merge(authorManager.getAuthoritiesByToken(token));
     CreateRootNode(nodes);
 }
Example #33
0
        public void UpdateChart()
        {
            try
            {
                OleDbConnection connection = new OleDbConnection();
                connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + reference.Getdb();
                connection.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT print_report.[ID], print_report.[printer_id], print_report.[overall_pagecount], print_report.[color_pagecount], print_report.[mono_pagecount], print_report.[date_time], base_count.[printer_id], base_count.[overall_pagecount] AS baseo, base_count.[color_pagecount] AS basec, base_count.[mono_pagecount] AS basem, print_report.[overall_pagecount] - [baseo] AS totalo, print_report.[color_pagecount] - [basec] AS totalc, print_report.[mono_pagecount] - [basem] AS totalm FROM print_report INNER JOIN base_count ON format(DateAdd('h',1,base_count.[date_time]),'mm/dd/yyyy hh') = format(print_report.[date_time], 'mm/dd/yyyy hh') WHERE print_report.[printer_id] = " + currentchart + " and base_count.[printer_id] = " + currentchart + " and print_report.[overall_pagecount] > 0 and base_count.[overall_pagecount] > 0 and Format(TimeSerial(Hour(print_report.[date_time]),0,0),'Short Time') <= '" + stop_time + "' and INT(print_report.date_time) >= DateValue('" + start + "') and INT(print_report.date_time) <= DateValue('" + stop + "') and Format(TimeSerial(Hour(base_count.[date_time]),0,0),'Short Time') >= '" + start_time + "';", connection);
                DataTable table = new DataTable();
                adapter.Fill(table);
                adapter.Dispose();
                if (live_tracking_checkbox.Checked)
                {
                    adapter = new OleDbDataAdapter("SELECT print_report.[ID], print_report.[printer_id], print_report.[overall_pagecount], print_report.[color_pagecount], print_report.[mono_pagecount], print_report.[date_time], base_count.[printer_id], base_count.[overall_pagecount] AS baseo, base_count.[color_pagecount] AS basec, base_count.[mono_pagecount] AS basem, print_report.[overall_pagecount] - [baseo] AS totalo, print_report.[color_pagecount] - [basec] AS totalc, print_report.[mono_pagecount] - [basem] AS totalm FROM print_report INNER JOIN base_count ON format(DateAdd('h',1,base_count.[date_time]),'mm/dd/yyyy hh') = format(print_report.[date_time], 'mm/dd/yyyy hh') WHERE print_report.[printer_id] = " + currentchart + " and base_count.[printer_id] = " + currentchart + " and print_report.[overall_pagecount] > 0 and Format(TimeSerial(Hour(print_report.[date_time]),0,0),'Short Time') = '" + DateTime.Now.AddHours(-1).ToString("HH:") + "00" + "' and print_report.date_time > DateValue('" + DateTime.Now + "') and Format(TimeSerial(Hour(base_count.[date_time]),0,0),'Short Time') = '" + start_time + "';", connection);
                    DataTable table2 = new DataTable();
                    adapter.Fill(table2);
                    table.Merge(table2);

                    adapter.Dispose();
                }
                connection.Close();

                printed_pages_chart.DataSource = table;
                printed_pages_chart.ChartAreas[0].AxisX.LabelStyle.Format = "M/d/yy htt";
                printed_pages_chart.Series.Clear();
                printed_pages_chart.Series.Add("Total");
                printed_pages_chart.Series["Total"].XValueMember = "date_time";
                printed_pages_chart.Series["Total"].YValueMembers = "totalo";
                printed_pages_chart.Series["Total"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
                printed_pages_chart.Series["Total"].IsValueShownAsLabel = true;
                printed_pages_chart.Series.Add("Color");
                printed_pages_chart.Series["Color"].XValueMember = "date_time";
                printed_pages_chart.Series["Color"].YValueMembers = "totalc";
                printed_pages_chart.Series["Color"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
                printed_pages_chart.Series["Color"].IsValueShownAsLabel = true;
                printed_pages_chart.Series.Add("Mono");
                printed_pages_chart.Series["Mono"].XValueMember = "date_time";
                printed_pages_chart.Series["Mono"].YValueMembers = "totalm";
                printed_pages_chart.Series["Mono"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.DateTime;
                printed_pages_chart.Series["Mono"].IsValueShownAsLabel = true;

                foreach(System.Windows.Forms.DataVisualization.Charting.Series s in printed_pages_chart.Series)
                {
                    foreach (System.Windows.Forms.DataVisualization.Charting.DataPoint dp in s.Points)
                    {
                        if (dp.YValues[0] == 0)
                        {
                            dp.IsValueShownAsLabel = false;
                        }
                    }

                }
                printed_pages_chart.DataBind();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
Example #34
0
        public void ProcessRequest(HttpContext context)
        {
            DataSet ds = new DataSet();
            string mode = context.Request["hmode"];
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            if (mode == "get_dropdown" || mode == "get_customerjob" || mode == "get_GridPopup" || mode == "get_prod_details" || mode == "get_prod_update")
            {
                object[] ob = new object[15];
                ob[0] = Convert.ToInt32(context.Request["PurchaseOrderID"]);
                ob[1] = Convert.ToInt32(context.Request["PrurchaseOrderDetailID"]);
                ob[2] = Convert.ToInt32(context.Request["BranchID"]);
                ob[3] = context.Request["PrurchaseOrderNo"];
                ob[4] = Convert.ToInt32(context.Request["Year"]);
                ob[5] = Convert.ToInt32(context.Request["ProductID"]);
                ob[6] = context.Request["ProductCode"];
                ob[7] = Convert.ToInt32(context.Request["PartyID"]);
                ob[8] = Convert.ToInt32(context.Request["JOBID"]);
                ob[9] = Convert.ToInt32(context.Request["IndentID"]);
                ob[10] = context.Request["ScreenName"];

                ob[11] = Convert.ToInt32(context.Request["CompanyID"]);
                ob[12] = context.Request["iMode"];

                ob[13] = Convert.ToInt32(context.Request["CreatedBy"]);
                ob[14] = Convert.ToInt32(context.Request["ModifiedBy"]);

                ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "[spu_PurchaseOrderSearch]", ob);
                if (ds.Tables.Count > 0)
                {
                    if (mode == "get_dropdown" || mode == "get_prod_update")
                    {
                        DataTable dt = new DataTable();
                        for (int i = 0; i < ds.Tables.Count; i++)
                        {
                            dt.Merge(ds.Tables[i]);
                        }
                        context.Response.Write(Json.GetJson(dt));
                    }
                    else
                    {
                        context.Response.Write(Json.GetJson(ds.Tables[0]));

                    }

                }
            }
            else
            {
                object[] ob = new object[2];
                ob[0] = context.Request["ScreenName"];
                ob[1] = Convert.ToInt32(context.Request["CompanyID"]);
                ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "[spu_AutoGenTransaction]", ob);
                if (ds.Tables.Count > 0)
                {
                    context.Response.Write(Json.GetJson(ds.Tables[0]));
                }
            }
        }
Example #35
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                DataSet ds = new DataSet();
                string mode = context.Request["handler_mode"];
                if (mode == "save_Product" || mode == "get_autocode" || mode == "update_Product" || mode == "fetch_Product" || mode == "get_dropdown")
                {
                    object[] ob = new object[19];
                    ob[0] = Convert.ToInt32(context.Request["ProductID"]);
                    ob[1] = Convert.ToInt32(context.Request["CompanyID"]);
                    ob[2] = Convert.ToInt32(context.Request["CategoryID"]);
                    ob[3] = context.Request["Description"];
                    ob[4] = Convert.ToInt32(context.Request["UOMID"]);
                    ob[5] = Convert.ToDecimal(context.Request["BuyPrice"]);
                    ob[6] =  Convert.ToDecimal(context.Request["SalePrice"]);
                    ob[7] = context.Request["ProductCode"];
                    ob[8] = context.Request["ProductStatus"];
                    ob[9] = Convert.ToInt32(context.Request["CreatedBy"]);
                    ob[10] = context.Request["CreatedOn"];
                    ob[11] = Convert.ToInt32(context.Request["ModifiedBy"]);
                    ob[12] = context.Request["ModifiedOn"];
                    ob[13] = context.Request["ProductGroupID"];
                    ob[14] = context.Request["ScreenName"];
                    ob[15] = context.Request["iMode"];
                    ob[16] = context.Request["InventoryType"];
                    ob[17] = context.Request["ARNO"];
                    ob[18] = context.Request["APNo"];
                    ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "[spu_Product]", ob);
                }
                else
                {
                    object[] ob = new object[1];
                    ob[0] = context.Request["ScreenName"];
                    ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "[spu_AutoGenMaster]", ob);
                }
                context.Response.ContentType = "application/json";
                context.Response.ContentEncoding = Encoding.UTF8;
                if (mode == "get_dropdown" || mode == "get_prod_update")
                {
                    DataTable dt = new DataTable();
                    for (int i = 0; i < ds.Tables.Count; i++)
                    {
                        dt.Merge(ds.Tables[i]);
                    }
                    context.Response.Write(Json.GetJson(dt));
                }
                else
                {
                    context.Response.Write(Json.GetJson(ds.Tables[0]));

                }

            }
            catch (Exception e)
            {
            }
        }
Example #36
0
 /// <summary>
 /// Returns dataTable with S. No. column
 /// </summary>
 /// <returns>DataTable</returns>
 protected DataTable GetTableWithSno(DataTable table)
 {
     DataTable RetVal = new DataTable();
     RetVal.Columns.Add(DILanguage.GetLanguageString("SERIAL_NUMBER"));
     RetVal.Columns[0].AutoIncrement = true;
     RetVal.Columns[0].AutoIncrementSeed = 1;
     RetVal.Merge(table, true, MissingSchemaAction.AddWithKey);
     return RetVal;
 }
Example #37
0
        public static DataTable CompareTwoDataTable(DataTable dt1, DataTable dt2)
        {
            dt1.Merge(dt2);

            DataTable d3 = dt2.GetChanges();


            return(d3);
        }
 public DataTable searchRequisitionTrend(string status, List<string> monthYearList,string department,string category)
 {
     DataTable dt = new DataTable();
     for (int i = 0; i < monthYearList.Count; i++)
     {
         dt.Merge(reqTrendFaca.getRequisitionTrendByCriteria(status, monthYearList[i].ToString(),department,category));
     }
     return dt;
 }
 public DataTable searchPurchasOrder(List<string> monthYearList, string supplier, string category)
 {
     DataTable dt = new DataTable();
     for (int i = 0; i < monthYearList.Count; i++)
     {
         dt.Merge(purchaseOrderFaca.getPurchaseOrderByCriteria(monthYearList[i].ToString(), supplier, category));
     }
     return dt;
 }
Example #40
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                DataSet ds = new DataSet();
                context.Response.ContentType = "application/json";
                context.Response.ContentEncoding = Encoding.UTF8;
                object[] ob = new object[25];
                ob[0] = context.Request["Tittle"];
                ob[1] = context.Request["Type"];
                ob[2] =  Convert.ToDateTime((context.Request["Startdate"] == "" ? "1990/1/1" : context.Request["Startdate"]));
                ob[3] = Convert.ToDateTime((context.Request["Starttime"] == "" ? "1990/1/1" : context.Request["Starttime"]));
                ob[4] =  Convert.ToDateTime((context.Request["Enddate"] == "" ? "1990/1/1" : context.Request["Enddate"]));
                ob[5] = Convert.ToDateTime((context.Request["Endtime"] == "" ? "1990/1/1" : context.Request["Endtime"]));
                ob[6] = Convert.ToInt32((context.Request["StatusID"] == "" ? "0" : context.Request["StatusID"]));
                ob[7] = context.Request["Notification"];
                ob[8] = Convert.ToInt32((context.Request["ActivityID"] == "" ? "0" : context.Request["ActivityID"]));
                ob[9] = context.Request["Location"];
                ob[10] = Convert.ToInt32((context.Request["PriorityID"] == "" ? "0" : context.Request["PriorityID"]));
                ob[11] = Convert.ToInt32((context.Request["VisibilityID"] == "" ? "0" : context.Request["VisibilityID"]));
                ob[12] = Convert.ToInt32((context.Request["RelatedTypeID"] == "" ? "0" : context.Request["RelatedTypeID"]));
                ob[13] = Convert.ToInt32((context.Request["RelateToID"] == "" ? "0" : context.Request["RelateToID"]));
                ob[14] = context.Request["Backgroundcolor"];
                ob[15] = context.Request["URL"];
                ob[16] = Convert.ToInt32((context.Request["CreatedBy"] == "" ? "0" : context.Request["CreatedBy"]));
                ob[17] = Convert.ToDateTime((context.Request["CreatedOn"] == "" ? "1990/1/1" : context.Request["CreatedOn"]));
                ob[18] = Convert.ToInt32((context.Request["ModifiedBy"] == "" ? "0" : context.Request["ModifiedBy"]));
                ob[19] =  Convert.ToDateTime((context.Request["ModifiedOn"] == "" ? "1990/1/1" : context.Request["ModifiedOn"]));
                ob[20] = Convert.ToInt32((context.Request["BranchID"] == "" ? "0" : context.Request["BranchID"]));
                ob[21] = Convert.ToInt32((context.Request["CompanyID"] == "" ? "0" : context.Request["CompanyID"]));
                ob[22] = context.Request["Descriptions"];
                ob[23] = context.Request["iMode"];
                ob[24] = Convert.ToInt32((context.Request["EventsId"] == "" ? "0" : context.Request["EventsId"]));
                ds = MSDataAccess.DataAccess.ExecuteDataset(Json.get_connectionstring(), "[spu_Events]", ob);
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables.Count > 1)
                    {
                        DataTable dt = new DataTable();
                        for (var i = 0; i < ds.Tables.Count; i++)
                        {
                            dt.Merge(ds.Tables[i]);
                        }
                        context.Response.Write(Json.GetJson(dt));
                    }
                    else
                    {
                        context.Response.Write(Json.GetJson(ds.Tables[0]));
                    }

                }
            }
            catch (Exception e)
            {

            }
        }
 public static DataTable BuildDataTableFromListOfFilenames(IList<object> listOfInputFiles)
 {
     var retval = new DataTable();
     foreach (var file in listOfInputFiles)
     {
         retval.Merge(GetDataTableFromCsvPath(file.ToString()));
     }
     return retval;
 }
        public ActionResult ExportExcel(string DepartmentId, string SectionId, string YearId, string MonthId, string MatNameId)
        {
            try
            {
                DataTable templateData = new DataTable();
                // add IEnumerable<AdjustAcceptedViewModels>
                List<AdjustAcceptedViewModels> viewModel = new List<AdjustAcceptedViewModels>();

                //filter department
                var q = from d in objBs.acceptedDelayBs.GetByFilter(DepartmentId, SectionId, Convert.ToInt32(MonthId), Convert.ToInt32(YearId))
                        select d;

                //filter matname
                if (!String.IsNullOrEmpty(MatNameId))
                {
                    q = q.Where(x => x.MATFRIGRP == MatNameId);
                }

                //int c = q.Count();

                foreach (var item in q)
                {
                    AdjustAcceptedViewModels model = new AdjustAcceptedViewModels();
                    model.Shipment = item.SHPMNTNO;
                    model.CarrierId = item.CARRIER_ID;
                    model.RegionId = item.REGION_ID;
                    model.RegionName = item.REGION_NAME_TH;
                    model.Soldto = item.SOLDTO;
                    model.SoldtoName = item.SOLDTO_NAME;
                    model.Shipto = item.SHIPTO;
                    model.Segment = item.SEGMENT;
                    model.SubSegment = item.SUBSEGMENT;
                    model.ShiptoName = item.LAST_SHPG_LOC_NAME;
                    model.ShippingPoint = item.SHPPOINT;
                    model.TruckType = item.TRUCK_TYPE;
                    model.LastTender = item.LTNRDDATE.Value.ToString("dd/MM/yyyy HH:mm", new CultureInfo("th-TH"));
                    model.PlanAccept = item.PLNACPDDATE.Value.ToString("dd/MM/yyyy HH:mm", new CultureInfo("th-TH"));
                    model.LastAccept = item.LACPDDATE.Value.ToString("dd/MM/yyyy HH:mm", new CultureInfo("th-TH"));
                    viewModel.Add(model);
                }
                templateData.Merge(ExcelModels.ToDataTable(viewModel));
                templateData.Columns.Add("Remark", typeof(string));

                ExcelModels ex = new ExcelModels();
                ex.DumpExcel(templateData, "ExportedAdjustAccept_" + DateTime.Now.ToString("yyyyMMddHHmm", new CultureInfo("th-TH")));//dump

                return View();
            }
            catch (Exception e)
            {
                TempData["Msg"] = "Error" + e.ToString();
                return View();
            }
        }
Example #43
0
        private void GetNextRows()
        {
            int topRowIndex = grdView.TopRowIndex;

            if ((grdView.IsLastRow) && (grdView.RowCount > 0))
            {
                System.Data.DataRow Row = grdView.GetDataRow(grdView.GetSelectedRows()[0]);
                string lastSubCodeId    = Row["SUBCODEID"].ToString();

                itemTable.Merge(GetInfoCodeList(lastSubCodeId, this.textBox.Text, DefaultNumberOfRows));
                grdView.TopRowIndex = topRowIndex;
            }
        }
        public static DataTable GetReceiptStatusList()
        {
            string query =
                HCMIS.Repository.Queries.Receipt.SelectGetReceiptStatusList();
            Receipt receipt = new Receipt();

            receipt.LoadFromRawSql(query);
            System.Data.DataTable tbl = receipt.DataTable;
            query = HCMIS.Repository.Queries.Receipt.SelectGetReceiptStatusList2();
            receipt.FlushData();
            receipt.LoadFromRawSql(query);

            tbl.Merge(receipt.DataTable);
            return(tbl);
        }
Example #45
0
        public void LoadSucKhoe()
        {
            if (cbLop.SelectedItem != null)
            {
                int    malop   = (int)cbLop.SelectedValue;
                string thangdo = cbThangdo.SelectedItem.ToString();


                System.Data.DataTable dths = HocSinhBUS.Instance.GetHocSinh(malop);
                dths.PrimaryKey = new DataColumn[]
                {
                    dths.Columns["MAHS"]
                };
                System.Data.DataTable dtsk = SucKhoeBUS.Instance.GetSucKhoe(malop, Convert.ToInt32(thangdo));
                dtsk.PrimaryKey = new DataColumn[]
                {
                    dtsk.Columns["MAHS"]
                };

                dths.Merge(dtsk);
                dgvSK.DataSource         = dths;
                dgvSK.Columns[0].Visible = true;  //cot stt
                dgvSK.Columns[1].Visible = false; //cot mahs
                dgvSK.Columns[5].Visible = false; //cot mask



                dgvSK.Columns[10].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dgvSK.Columns[2].AutoSizeMode  = DataGridViewAutoSizeColumnMode.Fill;

                dgvSK.Columns[0].ReadOnly = true;
                dgvSK.Columns[2].ReadOnly = true;
                dgvSK.Columns[3].ReadOnly = true;
                dgvSK.Columns[4].ReadOnly = true;



                dgvSK.Columns[2].HeaderText  = "Họ tên";
                dgvSK.Columns[3].HeaderText  = "Giới tính";
                dgvSK.Columns[4].HeaderText  = "Ngày sinh";
                dgvSK.Columns[6].HeaderText  = "Chiều cao";
                dgvSK.Columns[7].HeaderText  = "ĐGCC";
                dgvSK.Columns[8].HeaderText  = "Cân nặng";
                dgvSK.Columns[9].HeaderText  = "ĐGCN";
                dgvSK.Columns[10].HeaderText = "Đánh giá";
            }
        }
Example #46
0
        private void GetAllDataProduct(int currentPageNumber, int rowPerPage)
        {
            dtMain = new System.Data.DataTable();
            int skipRecord = currentPageNumber - 1;

            if (skipRecord != 0)
            {
                skipRecord = skipRecord * rowPerPage;
            }

            string query = "SELECT Barcode, Kyhieu [Ký Hiệu], MASP [Mã Sản Phẩm], Dai [Dài], Rong [Rộng], ART.Ten [ART], Color.Ten [Sơn], DVT, Product.Mieuta [Miêu tả] FROM [Product] Join ART on ART.ArtID = Product.ArtID join Color on Color.SonID = Product.SonID Order by Product.Ngaysua " + " OFFSET " + skipRecord.ToString() + " ROWS FETCH NEXT " + rowPerPage.ToString() + " ROWS ONLY; ";

            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            {
                using (SqlCeCommand command = new SqlCeCommand(query, connection))
                {
                    SqlCeDataAdapter      sda = new SqlCeDataAdapter(command);
                    System.Data.DataTable dt  = new System.Data.DataTable();
                    sda.Fill(dt);
                    dtMain.Merge(dt);
                    dvgProduct.DataSource           = dtMain;
                    dvgProduct.Columns["Dài"].Width = 60;
                    this.dvgProduct.Columns["Dài"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dvgProduct.Columns["Rộng"].Width = 60;
                    this.dvgProduct.Columns["Rộng"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dvgProduct.ColumnHeadersDefaultCellStyle.Alignment         = DataGridViewContentAlignment.MiddleCenter;
                    if (dtMain.Rows.Count > 0)
                    {
                        txtKyhieuFilter.Visible = true;
                        txtMaSPFilter.Visible   = true;
                        txtDaiFilter.Visible    = true;
                        txtRongFilter.Visible   = true;
                        txtArtFilter.Visible    = true;
                        txtSonFilter.Visible    = true;
                    }
                    else
                    {
                        txtKyhieuFilter.Visible = false;
                        txtMaSPFilter.Visible   = false;
                        txtDaiFilter.Visible    = false;
                        txtRongFilter.Visible   = false;
                        txtArtFilter.Visible    = false;
                        txtSonFilter.Visible    = false;
                    }
                }
            }
        }
        protected override void Execute(NativeActivityContext context)
        {
            destination = new System.Data.DataTable();
            source      = new System.Data.DataTable();
            try
            {
                destination = Destination.Get(context);
                source      = Source.Get(context);

                destination.Merge(source, false, MissingSchema_Action);
                Logger.Log.Logger.LogData(" Datatable merged Successfully", LogLevel.Info);
            }
            catch (Exception ex)
            {
                Logger.Log.Logger.LogData("Exception: Merging DataTable: " + ex.Message, LogLevel.Error);
            }
        }
Example #48
0
        private void GetAllData(int currentPageNumber, int rowPerPage, string strSearch)
        {
            dtMain = new DataTable();
            int skipRecord = currentPageNumber - 1;

            if (skipRecord != 0)
            {
                skipRecord = skipRecord * rowPerPage;
            }


            string query = "Select  DISTINCT(NewProduct.Kyhieu) [Ký Hiệu], NewProduct.MaSP [Mã Sản Phẩm],New.[BTP Chưa in], New.[BTP Đã in], New.[Thành Phẩm], New.[Sản phẩm lỗi], Stock.Mieuta [Miêu tả]  from Stock  join(SELECT Barcode, Kyhieu, MaSP from Product Group by Kyhieu, MaSP, Barcode)NewProduct on Stock.Barcode = NewProduct.Barcode join(SELECT Barcode, SUM(CASE WHEN LoaiID = 0000001 Then Soluongcon ELSE 0 END)[BTP Chưa in], SUM(CASE WHEN LoaiID = 0000002 Then Soluongcon ELSE 0 END)[BTP Đã in], SUM(CASE WHEN LoaiID = 0000003 Then Soluongcon ELSE 0 END)[Thành Phẩm], SUM(CASE WHEN LoaiID = 000004 Then Soluongcon ELSE 0 END)[Sản phẩm lỗi] FROM Stock " + strSearch + " GROUP BY Barcode) New on New.Barcode = Stock.Barcode  order by [Ký Hiệu] OFFSET " + skipRecord.ToString() + " ROWS FETCH NEXT " + rowPerPage.ToString() + " ROWS ONLY; ";

            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            {
                using (SqlCeCommand command = new SqlCeCommand(query, connection))
                {
                    SqlCeDataAdapter sda = new SqlCeDataAdapter(command);
                    DataTable        dt  = new DataTable();
                    sda.Fill(dt);
                    dtMain.Merge(dt);
                    dvgStock.DataSource = dtMain;
                    //dgvOrder.Columns[0].Visible = false;
                    //dgvOrder.Columns[1].Visible = false;
                    //dgvOrder.Columns[3].Width = 130;
                    dvgStock.Columns[1].DefaultCellStyle.Format = "dd/MM/yyyy HH:mm:ss";
                    dvgStock.Columns[1].Width = 150;
                    //dgvOrder.Columns[4].DefaultCellStyle.Format = "dd/MM/yyyy HH:mm:ss";
                    //dgvOrder.Columns[2].Width = 150;
                    //dgvOrder.Columns["Ký Hiệu"].Width = 60;
                    dvgStock.Columns["BTP Chưa in"].Width = 100;
                    this.dvgStock.Columns["BTP Chưa in"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dvgStock.Columns["BTP Đã in"].Width = 100;
                    this.dvgStock.Columns["BTP Đã in"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dvgStock.Columns["Thành Phẩm"].Width = 100;
                    this.dvgStock.Columns["Thành Phẩm"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dvgStock.Columns["Sản phẩm lỗi"].Width = 100;
                    this.dvgStock.Columns["Sản phẩm lỗi"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                    dvgStock.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                }
            }
        }
Example #49
0
        /// <summary>
        /// Permet de fusionner tous les schémas en une table
        /// </summary>
        /// <param name="tables"></param>
        /// <returns></returns>
        public static System.Data.DataTable DataTableMergeSchemas(params System.Data.DataTable[] tables)
        {
            if (tables == null || tables.Length == 0)
            {
                return(null);
            }
            //if (tables.Length == 1) return tables[0];
            System.Data.DataTable retour = tables.FirstOrDefault().Clone();

            foreach (var itemtable in tables) // parcour des tables
            {
                var clontable = itemtable.Clone();
                retour.Merge(clontable, true, System.Data.MissingSchemaAction.Add);

                //foreach (var itemcol in itemtable.Columns)
                //{
                //    if(itemtable.Columns.Contains()
                //}
            }

            return(retour);
        }
Example #50
0
 public void LoadDataByVin(DataView vins)
 {
     //string sql = "select * from DATA_CHANGE where vin in ("+vins+")";
     //DataSet ds = AccessHelper.ExecuteDataSet(AccessHelper.conn, sql, null);
     try
     {
         if (vins != null && vins.Table.Rows.Count > 0)
         {
             System.Data.DataTable dt = (System.Data.DataTable)gridControl1.DataSource;
             if (dt != null)
             {
                 dt.Merge(vins.Table);
                 string[] strComuns = { "VIN", "CLXH", "TYMC", "RLLX", "CT_ZHGKRLXHL", "ZCZBZL", "CT_BSQXS", "ZWPS", "UPDATEFIELD", "FIELDOLD", "FIELDNEW", "APPLYTYPE" };
                 dt = dt.AsDataView().ToTable(true, strComuns);
                 gridControl1.DataSource = dt;
             }
             else
             {
                 string[] strComuns           = { "VIN", "CLXH", "TYMC", "RLLX", "CT_ZHGKRLXHL", "ZCZBZL", "CT_BSQXS", "ZWPS", "UPDATEFIELD", "FIELDOLD", "FIELDNEW", "APPLYTYPE" };
                 System.Data.DataTable dtVins = vins.ToTable(true, strComuns);
                 gridControl1.DataSource = dtVins;
             }
             System.Data.DataView dv = ((System.Data.DataTable)gridControl1.DataSource).AsDataView();
             var insert_o            = dv.ToTable(true, "VIN", "APPLYTYPE").Select("APPLYTYPE='补传'");
             var update = dv.ToTable(true, "VIN", "APPLYTYPE").Select("APPLYTYPE='修改'");
             var delete = dv.ToTable(true, "VIN", "APPLYTYPE").Select("APPLYTYPE='撤销'");
             INSERT_O_SL.Text = insert_o.Length.ToString();
             UPDATE_SL.Text   = update.Length.ToString();
             DELETE_SL.Text   = delete.Length.ToString();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #51
0
        /// <summary>
        /// Loads additional information about each essay from an excel sheet; most importantly the VST and CEFR scores.
        /// </summary>
        private void excelSheetButton_Click(object sender, EventArgs e)
        {
            DialogResult result = excelFileDialog.ShowDialog();

            outputBox.Text = "Loading data sheet...";
            outputBox.Update();

            if (result == DialogResult.OK)
            {
                string[] files = excelFileDialog.FileNames;

                if (debugging)
                {
                    debugBox.Text = "Opening excel file"; debugBox.Update();
                }

                try
                {
                    FileStream stream = System.IO.File.Open(excelFileDialog.FileNames[0], FileMode.Open, FileAccess.Read);
                    //Choose one of either 1 or 2
                    //1. Reading from a binary Excel file ('97-2003 format; *.xls)
                    //IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

                    if (debugging)
                    {
                        debugBox.Text = "opening excelReader"; debugBox.Update();
                    }
                    //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
                    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

                    if (debugging)
                    {
                        debugBox.Text = "Creating column names"; debugBox.Update();
                    }
                    //4. DataSet - Create column names from first row
                    excelReader.IsFirstRowAsColumnNames = true;
                    DataSet ds = excelReader.AsDataSet();

                    if (debugging)
                    {
                        debugBox.Text = "Closing excelReader"; debugBox.Update();
                    }
                    //6. Free resources (IExcelDataReader is IDisposable)
                    excelReader.Close();

                    if (debugging)
                    {
                        debugBox.Text = "Creating dtFinal"; debugBox.Update();
                    }
                    System.Data.DataTable dtFinal = new System.Data.DataTable();

                    if (debugging)
                    {
                        debugBox.Text = "Merging dtFinal"; debugBox.Update();
                    }
                    foreach (System.Data.DataTable tmp in ds.Tables)
                    {
                        dtFinal.Merge(tmp);
                    }

                    if (debugging)
                    {
                        debugBox.Text = "Adding columns to mainTable from dtFinal"; debugBox.Update();
                    }
                    foreach (DataColumn cl in dtFinal.Columns)
                    {
                        if (!mainTable.Columns.Contains(cl.ColumnName))
                        {
                            mainTable.Columns.Add(cl.ColumnName, cl.DataType);
                            if (!cl.DataType.Equals(typeof(string)))
                            {
                                chart1_xBox.Items.Add(cl.ColumnName.ToString());
                                chart1_yBox.Items.Add(cl.ColumnName.ToString());
                            }
                        }
                    }

                    DataRow[] foundRows;

                    int i = 0;
                    foreach (DataRow row in mainTable.Rows)
                    {
                        i++;
                        outputBox.Text = "Importing data for row " + i + " of " + mainTable.Rows.Count;
                        outputBox.Update();

                        if (debugging)
                        {
                            debugBox.Text = "Selecting row in dtFinal containing " + row["Code"]; debugBox.Update();
                        }
                        foundRows = dtFinal.Select("Code = \'" + row["Code"] + "'"); //Get matching rows from tables

                        if (foundRows.Length > 0)
                        {
                            foreach (DataColumn cl in foundRows[0].Table.Columns)
                            {
                                if (debugging)
                                {
                                    debugBox.Text = "Adding column " + cl.ColumnName + " to row " + row["Code"]; debugBox.Update();
                                }
                                if (row.Table.Columns.Contains(cl.ColumnName))
                                {
                                    row[cl.ColumnName] = foundRows[0][cl.ColumnName];
                                }
                            }
                        }

                        debugBox.Update();
                    }

                    outputBox.Text = "Done.";
                    outputBox.Update();
                }
                catch (Exception ex)
                {
                    outputBox.Text = "!!! Could not load data sheet. It may be open in another program.";
                    outputBox.Update();
                }
            }
        }
Example #52
0
        public static MsExcel._Workbook Shashade(MsExcel.Application appExcel)
        {
            _Workbook ExcelBooks = null;

            appExcel.Visible = false;
            ExcelBooks       = appExcel.Workbooks.Add();

            string     Sheet_Name  = "站点数据";
            _Worksheet ExcelSheets = TU.Add_Sheets(ExcelBooks, Sheet_Name);//添加一个sheet

            ExcelSheets.Name = Sheet_Name;

            System.Data.DataTable dalaopo = new System.Data.DataTable("dalaopo");
            dalaopo.Columns.Add("站点", typeof(double));  //
            dalaopo.Columns.Add("降水数据", typeof(double));


            System.Data.DataTable jieguoTB = new System.Data.DataTable();

            double[] n = new double[] { 129, 135, 128, 132, 99, 113, 157, 81, 70, 111, 78, 138, 103, 88, 110, 91 };
            double[] T = new double[] { 5, 10, 20, 50 };
            for (int i = 0; i < n.Length; i++)
            {
                List <double> gailvL = new List <double>();
                for (int j = 0; j < T.Length; j++)
                {
                    double gailv = 1 - 50 / (n[i] * T[j]);
                    gailvL.Add(gailv);
                }
                double[] gailvd = gailvL.ToArray();
                string[] gailvS = MYTUW.TUW.doublearrTOstring(gailvd);
                System.Data.DataTable jieguo = MYTUW.TUW.ArToDT1(gailvS);
                jieguoTB.Merge(jieguo);
            }
            #region

            /*   for (int i = 1; i < RawDataStr_A.Length; i++)
             * {
             *  char[] seperators = { ',' };
             *  string[] R_str1 = TU.ParseStringTo_Array<string>(RawDataStr_A[i], seperators);
             *
             *  double zhandian = Convert.ToDouble(R_str1[0]);
             *  string jiangshuistr = Convert.ToString(R_str1[R_str1.Length -1]);
             * double jiangshui= Convert.ToDouble(R_str1[R_str1.Length - 1]);
             *  if (Convert .ToDouble ( jiangshuistr) > 30000)
             *  {
             *      string housanwei = Convert.ToString(R_str1[R_str1.Length - 1]).Substring(Convert.ToString(R_str1[R_str1.Length - 1]).Length - 3);
             *     // Console.WriteLine(housanwei);
             *      if (Convert .ToDouble (housanwei)>500&& Convert.ToDouble(housanwei)!=700)
             *      {
             *          jiangshui = Convert.ToDouble(housanwei);
             *      }
             *     else
             *      {
             *          jiangshui = 1;
             *      }
             *
             *  }
             *  dalaopo.Rows.Add(zhandian, jiangshui * 0.1);
             *
             *
             * }
             * var groupNew = from row in dalaopo.AsEnumerable()
             *             group row by new
             *             {
             *                 zhandian = (row.Field<double>("站点"))
             *             }
             *             into groupRes
             *             orderby groupRes.Key.zhandian
             *            select groupRes;
             * //把分完组的每个表格放入DS中
             * DataSet RTB_Grp = new DataSet();
             * foreach (var eachGroup in groupNew)
             * {
             *  System.Data.DataTable TBMid1 = eachGroup.CopyToDataTable();
             *
             *  RTB_Grp.Tables.Add(TBMid1);
             * }
             * //对每天的数据进行处理并放入 Traffic_TB中RTB_Grp.Tables .Count
             * for (int i=0;i< RTB_Grp.Tables.Count; i++)
             *  {
             *  System.Data.DataTable meigezhandian = RTB_Grp.Tables[i];
             *  List<double> baoyurishu = new List<double>();
             *  List<double> quannianyuliang = new List<double>();
             *  for (int j=0;j < meigezhandian.Rows.Count;j++)
             *  {
             *      double yuliang = Convert.ToDouble(meigezhandian.Rows[j][1]);
             *      quannianyuliang.Add(yuliang);
             *      if (yuliang>50)
             *      {
             *          baoyurishu.Add(yuliang);
             *      }
             *  }
             *  double baoyutianshu = baoyurishu.Count;
             *  double baoyuliang = baoyurishu.Sum();
             *  double baoyuqiangdu = baoyuliang / baoyutianshu;
             *  double zongyuliang = quannianyuliang.Sum();
             *  double baoyugongxianlv = baoyuliang / zongyuliang;
             *  jieguoTB.Rows.Add(Convert.ToDouble(meigezhandian.Rows[0][0]), baoyutianshu,
             *     baoyuliang, baoyuqiangdu, baoyugongxianlv);
             * }
             */
            #endregion
            MYTUW.TUW.DTToExcel(jieguoTB, ExcelSheets, 2, 1);

            MYTUW.TUW.Delete_sheet(appExcel, ExcelBooks);
            return(ExcelBooks);
        }
Example #53
0
    protected void Page_Load(object sender, EventArgs e)
    {
        /*
         * recupere la liste des pays/villes/cp correspondant a la saisie de la recherche,
         * et retourne cette liste sous forme de liste deroulante
         * Utilise les parametres ?type=xxx&recherche=xxx dans l'url
         */

        string indentation = "";
        string onglet      = Request.QueryString["onglet"];    //Sert a choisir un margin suivant la page
        string type        = Request.QueryString["type"];      //in {ville,pays,cp}
        string recherche   = Request.QueryString["recherche"]; //Valeur saisie par l'utilisateur
        string style       = Request.QueryString["style"];     //Style css, valeur par defaut oui | si style = no, renvoie les donnes sans mise en page separe par un \n
        string cssClass    = "";

        switch (style)
        {
        case "no": cssClass = ""; break;

        case "mini": cssClass = "ajouterAcquereur_ClickableCellMini"; break;

        default: cssClass = "ajouterAcquereur_ClickableCell"; break;
        }



        if (onglet == "0")
        {
            indentation = "-220"; //onglet mandat
        }
        else if (onglet == "1")   //onglet vendeur
        {
            if (type == "cp")
            {
                indentation = "-130";
            }
            else if (type == "ville")
            {
                indentation = "-380";
            }
            else
            {
                indentation = "-216";
            }
        }
        else if (onglet == "2")
        {
            indentation = "-216";                       //onglet juridique
        }
        else if (onglet == "3")
        {
            indentation = "-216";                       //onglet proprietaire
        }
        else
        {
            indentation = "0";
        }

        string table    = "<div class='AjoutacquereurScrollCell100' style='z-index:2;background-color:#EFEFEF;position:absolute;margin-left:" + indentation + "px;margin-top:10px;padding-right:18px;'><table border='0'><tbody>";
        string tableend = "</tbody></table></div>";
        string result   = "";
        string query    = "";


        if (type != "" && recherche != "")
        {
            recherche = recherche.Replace("'", "''");
            int temp = 0;

            if (type == "all" || type == "pays")           //Recherche pour un pays
            {
                query = "select Titre_Pays from Pays WHERE Titre_Pays LIKE '%" + recherche + "%' ORDER BY Titre_Pays";

                Connexion c = new Connexion(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                c.Open();
                System.Data.DataSet ds = c.exeRequette(query);
                c.Close();
                c = null;

                System.Data.DataRowCollection dr = ds.Tables[0].Rows;


                foreach (System.Data.DataRow ligne in dr)
                {
                    string onclick = "saisiePays(this," + onglet + ")";
                    string nomLieu = ligne[0].ToString().ToUpper();
                    result += genererLigne(onclick, nomLieu, "bold " + cssClass);
                }
            }

            if (type == "all" || type == "dep")           //Recherche pour un dep
            {
                if (int.TryParse(recherche, out temp))
                {
                    string zero = (recherche.Length == 1)?"0":"";
                    query = "select departement_code,departement_nom from departement WHERE departement_code = '" + zero + recherche + "' ORDER BY departement_nom";
                }
                else
                {
                    query = "select departement_code,departement_nom from departement WHERE departement_slug LIKE '%" + recherche + "%' OR departement_nom LIKE '%" + recherche + "%' ORDER BY departement_nom";
                }

                Connexion c = new Connexion(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                c.Open();
                System.Data.DataSet ds = c.exeRequette(query);
                c.Close();
                c = null;

                System.Data.DataRowCollection dr = ds.Tables[0].Rows;



                foreach (System.Data.DataRow ligne in dr)
                {
                    string onclick = "saisieDep('" + ligne[1].ToString().Replace("'", "\\\'") + "'," + ligne[0] + "," + onglet + ")";
                    string nomLieu = ligne[1].ToString().ToUpper() + " (" + ligne[0] + ")";
                    result += genererLigne(onclick, nomLieu, "bold " + cssClass);
                }
            }

            if (type == "all" || type == "ville")    //Recherche pour une ville
            {
                //requete sql
                string query1 = "select Nom,[Code Postal],refpays from Ville WHERE Nom LIKE '%" + recherche + "%'";
                string query2 = "select Nom,[Code Postal],refpays from Arrondissement WHERE Nom LIKE '%" + recherche + "%'";

                //execution des 2 requete
                Connexion c = new Connexion(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                c.Open();
                System.Data.DataTable dt1 = c.exeRequette(query1).Tables[0];
                System.Data.DataTable dt2 = c.exeRequette(query2).Tables[0];
                c.Close();
                c = null;

                dt1.Merge(dt2);        //Fusion des 2 resultats
                DataView view = new DataView(dt1);
                view.Sort = "Nom ASC"; //Tri des resultat | Order by n'est pas utilise dans le sql vu qu'il faut fusionner apres

                foreach (System.Data.DataRowView ligne in view)
                {
                    if (ligne[1].ToString().Length > 5 && type != "all") //On ignore les villes regroupant plusieurs arrondissements (ayant un champ code postal contenant plus d'un cp)
                    {
                        continue;                                        //Pour afficher les arrondissements de maniere independantes
                    }
                    string onclick = "saisieVille('" + ligne[0].ToString().Replace("'", "\\\'") + "','" + ligne[1] + "'," + onglet + ")";
                    string pays    = "" + ligne[2].ToString();
                    string nomLieu = pays + ligne[0].ToString();
                    if (ligne[1].ToString().Length > 5)
                    {
                        nomLieu += " (Tous les arrondissements)";
                    }
                    else
                    {
                        nomLieu += " (" + ligne[1] + ")";
                    }
                    result += genererLigne(onclick, nomLieu, cssClass);
                }
            }



            if (type == "all" && int.TryParse(recherche, out temp) || type == "cp")  //Recherche pour un code postal
            {
                string query1 = "select Nom,[Code Postal] from Ville WHERE [Code Postal] LIKE '" + recherche + "%'";
                string query2 = "select Nom,[Code Postal] from Arrondissement WHERE [Code Postal] LIKE '" + recherche + "%'";

                Connexion c = new Connexion(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                c.Open();
                System.Data.DataTable dt1 = c.exeRequette(query1).Tables[0];
                System.Data.DataTable dt2 = c.exeRequette(query2).Tables[0];
                c.Close();
                c = null;

                dt1.Merge(dt2);
                DataView view = new DataView(dt1);
                view.Sort = "Nom ASC";

                foreach (System.Data.DataRowView ligne in view)
                {
                    if (ligne[1].ToString().Length > 5)
                    {
                        continue;
                    }

                    string onclick = "saisieVille('" + ligne[0].ToString().Replace("'", "\\\'") + "','" + ligne[1] + "'," + onglet + ")";
                    string nomLieu = ligne[0] + " (" + ligne[1] + ")";
                    result += genererLigne(onclick, nomLieu, cssClass);
                }
            }

            if (result != "")
            {
                Response.Write(table + result + tableend);
            }
        }
    }
    protected void btnSkillSearch_Click(object sender, EventArgs e)
    {
        try
        {
            string   SkillName = "";
            string[] Sk        = txtSkillSearch.Text.Split(',');
            int      fl        = 0;
            foreach (string s in Sk)
            {
                if (fl == 0)
                {
                    SkillName = "(JobSeekerSkillDetail.SkillName like '%" + s.Trim() + "%' ";
                    fl        = 1;
                }
                else
                {
                    SkillName += " or JobSeekerSkillDetail.SkillName like '%" + s.Trim() + "%' ";
                }
            }
            SkillName += ")";
            System.Data.DataTable dt = dl.Vacancy_SearchByEmployer_UsingDataBase_Display(bl, SkillName).Tables[0];

            string jid = "(0";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jid += "," + dt.Rows[i]["JobSeeker_ID"];
            }
            jid += ")";
            DataSet ds = dl.Vacancy_SearchByEmployer_NotExist_Display(bl, jid);

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                bl.JobSeeker_ID = Convert.ToInt32(ds.Tables[0].Rows[i]["JobSeeker_ID"].ToString());
                DataSet ds1 = dl.Vacancy_SearchByEmployer_RetriveResumeFileNotExist_Display(bl);
                if (ds1 != null && ds1.Tables[0].Rows.Count > 0)
                {
                    string resume = ds1.Tables[0].Rows[0]["ResumeFile"].ToString();

                    string filename = Server.MapPath("~/Resume/" + resume);
                    string ext      = System.IO.Path.GetExtension(filename);
                    if (ext.ToLower() == ".pdf")
                    {
                        StringBuilder strStreamValue = new StringBuilder();
                        using (PdfReader pr = new PdfReader(filename))
                        {
                            for (int pgno = 1; pgno <= pr.NumberOfPages; pgno++)
                            {
                                strStreamValue.Append(PdfTextExtractor.GetTextFromPage(pr, pgno));
                            }
                        }
                        foreach (string s in Sk)
                        {
                            if (strStreamValue.ToString().ToLower().Contains(s.ToLower()))
                            {
                                bl.JobSeeker_ID = Convert.ToInt32(ds.Tables[0].Rows[i]["JobSeeker_ID"].ToString());
                                System.Data.DataTable dtRes = dl.Vacancy_SearchByEmployer_UsingJobSeeker_ID_Display(bl).Tables[0];
                                dt.Merge(dtRes);

                                break;
                            }
                        }
                    }
                    else if (ext.ToLower() == ".doc" || ext.ToLower() == ".docx")
                    {
                        // create word application
                        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.ApplicationClass();
                        // create object of missing value
                        object miss = System.Reflection.Missing.Value;
                        // create object of selected file path
                        object path = filename;
                        // set file path mode
                        object readOnly = true;
                        // open document
                        Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
                        // select whole data from active window document
                        docs.ActiveWindow.Selection.WholeStory();
                        // handover the data to cllipboard
                        docs.ActiveWindow.Selection.Copy();
                        // clipboard create reference of idataobject interface which transfer the data
                        // string ttt = Clipboard.GetText();
                        string ttt1 = docs.Content.Text;
                        docs.Close(ref miss, ref miss, ref miss);
                        foreach (string s in Sk)
                        {
                            if (ttt1.ToLower().Contains(s.ToLower()))
                            {
                                bl.JobSeeker_ID = Convert.ToInt32(ds.Tables[0].Rows[i]["JobSeeker_ID"].ToString());
                                System.Data.DataTable dtRes = dl.Vacancy_SearchByEmployer_UsingJobSeeker_ID_Display(bl).Tables[0];
                                dt.Merge(dtRes);

                                break;
                            }
                        }
                    }
                }
            }
            GVVacancyInfo.DataSource = dt;
            GVVacancyInfo.DataBind();
        }
        catch
        {
            lblMsg.ForeColor = System.Drawing.Color.Red;
            lblMsg.Text      = "Technical error";
        }
    }
Example #55
0
    /// <summary>
    /// 读取excel ,默认第一行为标头
    /// </summary>
    /// <param Name="strFileName">excel文档路径</param>
    /// <returns></returns>
    public int Import(string strFileName)
    {
        try
        {
            Excel_dt = new DataTable();
            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int  cellCount = headerRow.LastCellNum;
            for (int j = 0; j < cellCount; j++)
            {
                Excel_dt.Columns.Add(j.ToString());
            }
            DataRow title = Excel_dt.NewRow();//标题
            title[0] = sheet.GetRow(0).ToString();
            Excel_dt.Rows.Add(title);
            DataRow term = Excel_dt.NewRow();//学期
            term[0] = sheet.GetRow(1).ToString();
            Excel_dt.Rows.Add(term);
            DataRow classinfo = Excel_dt.NewRow();//课程专业
            classinfo[0] = sheet.GetRow(2).GetCell(0).ToString();
            classinfo[1] = sheet.GetRow(2).GetCell(4).ToString();
            Excel_dt.Rows.Add(classinfo);

            DataRow student = Excel_dt.NewRow();//年级和班级
            student[0] = sheet.GetRow(3).GetCell(0).ToString();
            student[1] = sheet.GetRow(3).GetCell(4).ToString();
            Excel_dt.Rows.Add(student);

            DataRow book = Excel_dt.NewRow();//教材
            book[0] = sheet.GetRow(4).GetCell(0).ToString();
            Excel_dt.Rows.Add(book);

            //headerRow = sheet.GetRow(5);


            for (int i = 5; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row != null)
                {
                    DataRow dataRow = Excel_dt.NewRow();

                    for (int j = 0; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                        {
                            dataRow[j] = row.GetCell(j).ToString();
                        }
                    }
                    Excel_dt.Rows.Add(dataRow);
                }
                else
                {
                    break;
                }
            }

            int[] name = new int[7];//确定Excel的所需字段值所在的列---
            daClass = helper.adapter(strSelect_Class_Data);
            dtClass = new System.Data.DataTable();
            daClass.Fill(dtClass);
            daClass.FillSchema(dtClass, SchemaType.Source);
            string classname = Excel_dt.Rows[2][0].ToString();              //课程名称
            string spcialty  = Excel_dt.Rows[2][1].ToString().Substring(3); //专业
            string banji     = Excel_dt.Rows[3][1].ToString();
            for (int q = 0; q < Excel_dt.Columns.Count; q++)
            {
                switch (Excel_dt.Rows[5][q].ToString())
                {
                case "周次": name[0] = q; break;

                case "星期": name[1] = q; break;

                case "节次": name[2] = q; break;

                case "上课地点": name[3] = q; break;

                case "授课教师": name[4] = q; break;

                case "授课内容": name[5] = q; break;

                case "授课方式": name[6] = q; break;
                }
            }

            dt = dtClass.Copy();   //  获取Class_Data的架构
            dt.Clear();
            for (int i = 6; i < Excel_dt.Rows.Count; i++)
            {
                // dr = dt.Rows[i];//获取Excel的当前操作行的数据
                if (!(Excel_dt.Rows[i][name[0]].ToString() == "周次" || Excel_dt.Rows[i][name[0]].ToString() == ""))
                {
                    string teachername = Excel_dt.Rows[i][name[4]].ToString(); //获取授课老师列的数据
                    int    k           = Teacher(teachername) + 1;             //判断有多少位老师上同一节课
                    for (int m = 1; m <= k; m++)                               //有几位老师,就循环几次
                    {
                        string teachernamepick;                                //定义截取的老师名字
                        //以逗号为分界点,把多位老师的名字分成各自的名字
                        if ((k == 1) || (m == k))
                        {
                            teachernamepick = teachername;
                        }
                        else
                        {
                            int index2 = teachername.IndexOf(",");
                            teachernamepick = teachername.Substring(0, index2);
                            teachername     = teachername.Remove(0, index2 + 1);
                        }


                        int j;
                        //判断星期几,返回对应的数字
                        switch (Excel_dt.Rows[i][name[1]].ToString().Substring(0, 1))
                        {
                        case "一": j = 1; break;

                        case "二": j = 2; break;

                        case "三": j = 3; break;

                        case "四": j = 4; break;

                        case "五": j = 5; break;

                        default: j = 0; break;
                        }
                        if (teachernamepick != null && teachernamepick != "")
                        {
                            DataRow drClass_information = dt.NewRow();
                            drClass_information["Class_Day"] = j;
                            //获取节次
                            string strclassname  = Excel_dt.Rows[i][name[2]].ToString();
                            int    classnumindex = strclassname.IndexOf("-");
                            drClass_information["Teacher"]       = teachernamepick;
                            drClass_information["Class_ID"]      = teachernamepick + Excel_dt.Rows[i][name[0]].ToString() + j.ToString() + strclassname.Substring(0, classnumindex) + strclassname.Substring(classnumindex + 1) + classname.Substring(5) + Excel_dt.Rows[i][name[3]] + banji;
                            drClass_information["Teacher_ID"]    = "0000000000";
                            drClass_information["Class_Week"]    = Excel_dt.Rows[i][name[0]];
                            drClass_information["Class_Number"]  = Convert.ToInt32(strclassname.Substring(0, classnumindex) + strclassname.Substring(classnumindex + 1));
                            drClass_information["Class_Address"] = Excel_dt.Rows[i][name[3]];
                            drClass_information["Class_Name"]    = classname.Substring(5);
                            drClass_information["Class_Content"] = Excel_dt.Rows[i][name[5]];
                            drClass_information["Class_Type"]    = Excel_dt.Rows[i][name[6]];
                            drClass_information["Spcialty"]      = spcialty;

                            dt.Rows.Add(drClass_information);
                        }
                        else
                        {
                            return(0);
                        }
                    }
                }
            }
            dtClass.Merge(dt, true);

            daClass.Update(dtClass);
            return(1);
        }
        catch (Exception)
        {
            return(0);
        }
    }
Example #56
0
        public static DateTime intervalTime2; //区间时间2


        public static void exportData()//导出
        {
            int exportNum = 0;

            try
            {
                MySqlConnection mycon = new MySqlConnection();
                mycon = getMycon();
                DateTime startTime = DateTime.Now;//计算程序运行时间
                string   str1      = getstr1();
                System.Data.DataTable tableName;
                if (MainForm.getInstance().TMname.Text == "DTS温度解调仪")
                {
                    tableName = drawingDTSDep.getTNameTable(intervalTime1, intervalTime2);
                    exportNum = 1;
                }
                else
                {
                    tableName = drawingGDep.getTNameTable(intervalTime1, intervalTime2);//获取需要使用的表名称
                }
                if (str1 != null)
                {
                    //string str3 = null;
                    //string str3num = null;
                    //System.Data.DataTable dtValue = new System.Data.DataTable();
                    //for (int i = 0; i < tableName.Rows.Count; i++)
                    //{
                    //    str3 = "SELECT Depth,RecordTime,TM from  " + tableName.Rows[i][0] + " " + str1;
                    //    str3num = str3num + str3 + " union ";
                    //}

                    string str3 = null;
                    // string str3num = null;
                    System.Data.DataTable dtValue = new System.Data.DataTable();
                    System.Data.DataTable dt      = new System.Data.DataTable();
                    for (int i = 0; i < tableName.Rows.Count; i++)
                    {
                        dt   = null;
                        str3 = null;
                        str3 = "SELECT Depth,RecordTime,TM from  " + tableName.Rows[i][0] + " " + str1 + " ORDER BY RecordTime";
                        dt   = getDataTable(str3, mycon);
                        dtValue.Merge(dt);
                    }

                    // str3num = str3num.Remove(str3num.Length - 6, 6) + " ORDER BY RecordTime, Depth";
                    //数据存入临时表


                    //获取文件名称
                    //  string saveFileName ;
                    SaveFileDialog saveDialog = new SaveFileDialog();
                    saveDialog.DefaultExt = "csv";
                    saveDialog.Filter     = "Excel文件|*.csv";

                    saveDialog.Title    = "请填写文件名和选择文件路径";
                    saveDialog.FileName = "新建";
                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        //saveFileName = saveDialog.FileName;
                        try
                        {
                            SaveCSV(dtValue, saveDialog.FileName, exportNum);
                            TimeSpan ts = DateTime.Now - startTime;
                            MessageBox.Show("文件: " + saveDialog.FileName + "保存成功,总共花费时间:" + ts.ToString(), "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            mycon.Close();
                        }
                        catch (Exception e)
                        {
                            MyClass.goTrue();
                            MessageBox.Show("导出失败" + e);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MyClass.goTrue();
                MessageBox.Show("导出失败" + ex);
            }
            MyClass.goTrue();
            //   MainForm.threadImport.Abort();
        }
Example #57
0
 private void readFilesTodtTable(String filePath)
 {
     System.Data.DataTable newdtTable = CsvHelper.CsvHelper.CsvParsingHelper.CsvToDataTable(filePath, true);
     dtTable.Merge(newdtTable);
 }
Example #58
0
        /// <summary>
        /// 合并按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            scoreDic.Clear();
            scoreList.Clear();
            tempDataTable.Clear();
            if (dataTables.Count <= 0)
            {
                MessageBox.Show("请先导入要合并的Excel表");
                return;
            }
            else if (dataTables.Count <= 1)
            {
                MessageBox.Show("请导入至少两个表");
                return;
            }
            for (int i = 0; i < dataTables.Count; i++)
            {
                string temp1 = dataTables[i].Rows[0]["F2"].ToString();
                string temp2 = string.Empty;
                if (i + 1 >= dataTables.Count)
                {
                    temp2 = temp1;
                }
                else
                {
                    temp2 = dataTables[i + 1].Rows[0]["F2"].ToString();
                }
                if (comboBox1.Text == comboBox1.Items[0].ToString())
                {
                    if (temp1 != temp2)
                    {
                        MessageBox.Show(string.Format("合并类型有误,请查看表{0},{1}重新选择合并类型", dataTables[i].TableName, dataTables[i + 1].TableName));
                        return;
                    }
                    else
                    {
                        tempDataTable.Merge(dataTables[i], true, MissingSchemaAction.AddWithKey);
                    }
                }
                else if (comboBox1.Text == comboBox1.Items[1].ToString())
                {
                    if (i + 1 >= dataTables.Count)
                    {
                        temp2 = "";
                    }
                    if (temp1 != temp2)
                    {
                        //总成绩合并
                        AddTable(tempDataTable, dataTables[i]);
                    }
                    else
                    {
                        MessageBox.Show(string.Format("合并类型有误,请查看表{0},{1}重新选择合并类型", dataTables[i].TableName, dataTables[i + 1].TableName));
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("合并类型有误,请重新选择");
                }
            }

            foreach (TabPage tempPage in tabCon_Excel.TabPages)
            {
                if (tempPage.Text == "合并表")
                {
                    MessageBox.Show("已存在合并表,不能重复合并");
                    return;
                }
            }
            if (comboBox1.Text == comboBox1.Items[1].ToString())
            {
                string id    = string.Empty;
                string value = string.Empty;
                for (int i = 0; i < tempDataTable.Columns.Count; i++)
                {
                    if (tempDataTable.Rows[0][tempDataTable.Columns[i]].ToString() == "总分")
                    {
                        if (i + 1 >= tempDataTable.Columns.Count)
                        {
                            break;
                        }
                        else
                        {
                            value = tempDataTable.Columns[i + 1].ColumnName.ToString();
                            scoreList.Add(value);
                        }
                    }
                }

                int        index      = tempDataTable.Columns.Count;
                DataColumn dataColumn = new DataColumn();
                dataColumn.ColumnName = "编号";
                tempDataTable.Columns.Add(dataColumn);
                for (int i = 1; i <= scoreList.Count; i++)
                {
                    DataColumn dataColumn1 = new DataColumn();
                    dataColumn1.ColumnName = "比赛项目" + i;
                    tempDataTable.Columns.Add(dataColumn1);
                }
                DataColumn column1 = new DataColumn();
                column1.ColumnName = "比赛总成绩";
                tempDataTable.Columns.Add(column1);
                for (int a = 0; a < tempDataTable.Rows.Count; a++)
                {
                    tempDataTable.Rows[a]["编号"] = tempDataTable.Rows[a][tempDataTable.Columns[0]];
                    double f = 0;
                    for (int b = 0; b < scoreList.Count; b++)
                    {
                        string tempColumnName = "比赛项目" + (b + 1);
                        string temp           = tempDataTable.Rows[a][scoreList[b]].ToString();
                        tempDataTable.Rows[a][tempColumnName] = tempDataTable.Rows[a][scoreList[b]];
                        f += Convert.ToDouble(tempDataTable.Rows[a][tempColumnName]);
                    }
                    tempDataTable.Rows[a]["比赛总成绩"] = f;
                }
            }
            TabPage page = new TabPage();

            page.Name = "Page" + tabCon_Excel.TabPages.Count;
            page.Text = "合并表";
            tabCon_Excel.Controls.Add(page);
            tabCon_Excel.SelectedTab = page;
            DataGridView dataGridView = new DataGridView();

            dataGridView.ReadOnly            = true;
            dataGridView.Parent              = page;
            dataGridView.Size                = page.Size;
            dataGridView.DataSource          = tempDataTable;
            dataGridView.AutoGenerateColumns = false;
        }
Example #59
0
        public static DataTable PivotData(this DataTable _SourceTable, string DataField, AggregateFunctionE Aggregate, string[] RowFields, string[] ColumnFields, Boolean isFindSummary = false)
        {
            DataTable dt        = new DataTable();
            string    Separator = ".";
            var       RowList   = _SourceTable.DefaultView.ToTable(true, RowFields).AsEnumerable().ToList();

            for (int index = RowFields.Count() - 1; index >= 0; index--)
            {
                RowList = RowList.OrderBy(x => x.Field <object>(RowFields[index])).ToList();
            }
            // Gets the list of columns .(dot) separated.

            //dt.Columns.Add(RowFields);
            foreach (string s in RowFields)
            {
                //Get dataType of the column

                if (_SourceTable.Columns[s].DataType.Name.ToLower().IndexOf("datetime") >= 0 || _SourceTable.Columns[s].DataType.Name.ToLower().IndexOf("date") >= 0)
                {
                    dt.Columns.Add(s, typeof(System.DateTime));
                }
                else if (_SourceTable.Columns[s].DataType.Name.ToLower().IndexOf("int") >= 0 || _SourceTable.Columns[s].DataType.Name.ToLower().IndexOf("double") >= 0 || _SourceTable.Columns[s].DataType.Name.ToLower().IndexOf("float") >= 0 || _SourceTable.Columns[s].DataType.Name.ToLower().IndexOf("decimal") >= 0)
                {
                    dt.Columns.Add(s, typeof(double));
                }
                else
                {
                    dt.Columns.Add(s);
                }
            }


            if (ColumnFields != null)
            {
                var ColList = (from x in _SourceTable.AsEnumerable()
                               select new
                {
                    Name = ColumnFields.Select(n => x.Field <object>(n))
                           .Aggregate((a, b) => a += Separator + b.ToString())
                })
                              .Distinct();
                //.OrderBy(m => m.Name);
                foreach (var col in ColList)
                {
                    if (col.Name != null)
                    {
                        dt.Columns.Add(col.Name.ToString(), typeof(double));  // Cretes the result columns.//
                    }
                }



                foreach (var RowName in RowList)
                {
                    DataRow row       = dt.NewRow();
                    string  strFilter = string.Empty;

                    foreach (string Field in RowFields)
                    {
                        row[Field] = RowName[Field];
                        strFilter += " and " + Field + " = '" + RowName[Field].ToString() + "'";
                    }
                    strFilter = strFilter.Substring(5);

                    foreach (var col in ColList)
                    {
                        string filter = strFilter;
                        if (col.Name != null)
                        {
                            string[] strColValues = col.Name.ToString().Split(Separator.ToCharArray(), StringSplitOptions.None);
                            for (int i = 0; i < ColumnFields.Length; i++)
                            {
                                if (strColValues[i] != null)
                                {
                                    filter += " and " + ColumnFields[i] + " = '" + strColValues[i] + "'";
                                }
                            }
                            object val = _SourceTable.Computing(filter, DataField, Aggregate);

                            if (val == null)
                            {
                                val = 0;
                            }
                            row[col.Name.ToString()] = val;
                        }
                    }
                    dt.Rows.Add(row);
                }
            }
            else
            {
                dt.Columns.Add(DataField, typeof(double));

                foreach (var RowName in RowList)
                {
                    DataRow row       = dt.NewRow();
                    string  strFilter = string.Empty;

                    foreach (string Field in RowFields)
                    {
                        row[Field] = RowName[Field];
                        strFilter += " and " + Field + " = '" + RowName[Field].ToString() + "'";
                    }
                    strFilter = strFilter.Substring(5);

                    row[DataField] = _SourceTable.Computing(strFilter, DataField, Aggregate);

                    dt.Rows.Add(row);
                }

                if (isFindSummary)
                {
                    for (int index = 0; index < RowFields.Count() - 1; index++)
                    {
                        DataTable _temp = new DataTable();
                        _temp = dt.Clone();

                        List <string> rFields = new List <string>();
                        DataTable     _dt     = new DataTable();
                        List <string> _disRow = new List <string>();


                        for (int rix = 0; rix < RowFields.Count() - 1; rix++)
                        {
                            if (index >= rix)
                            {
                                {
                                    rFields.Add(RowFields[rix]);
                                }
                            }
                        }


                        foreach (string i in rFields)
                        {
                            _disRow.Add(i);
                        }
                        _dt = _SourceTable.DefaultView.ToTable(true, _disRow.ToArray());



                        foreach (DataRow _dr in _dt.Rows)
                        {
                            DataRow dr        = _temp.NewRow();
                            string  strFilter = "";
                            foreach (string fn in _disRow)
                            {
                                dr[fn]     = _dr[fn];
                                strFilter += " and " + fn + " = '" + _dr[fn].ToString() + "'";
                            }
                            strFilter     = strFilter.Substring(5);
                            dr[DataField] = dt.Computing(strFilter, DataField, Aggregate);
                            _temp.Rows.Add(dr);
                        }
                        dt.Merge(_temp);
                    }
                }
            }


            for (int i = 0; i < dt.Columns.Count; i++)
            {
                dt.Columns[i].ColumnName = dt.Columns[i].ColumnName.Replace(" ", "_");
            }



            return(dt);
        }
Example #60
0
      public int ReadExcel(string ExcelPath)
      {
          try
          {
              int[] name = new int[7];   //确定Excel的所需字段值所在的列---
              daClass = helper.adapter(strSelect_Class_Data);
              dtClass = new System.Data.DataTable();
              daClass.Fill(dtClass);
              daClass.FillSchema(dtClass, SchemaType.Source);
              ExcelConnection(ExcelPath);
              //MessageBox.Show(Excel_dt.Columns[0].ToString());

              string classname = Excel_dt.Rows[1][0].ToString();              //课程名称
              string spcialty  = Excel_dt.Rows[1][4].ToString().Substring(3); //专业
              string banji     = Excel_dt.Rows[2][4].ToString();
              for (int q = 0; q < Excel_dt.Columns.Count; q++)
              {
                  switch (Excel_dt.Rows[4][q].ToString())
                  {
                  case "周次": name[0] = q; break;

                  case "星期": name[1] = q; break;

                  case "节次": name[2] = q; break;

                  case "上课地点": name[3] = q; break;

                  case "授课教师": name[4] = q; break;

                  case "授课内容": name[5] = q; break;

                  case "授课方式": name[6] = q; break;
                  }
              }

              dt = dtClass.Copy();      //  获取Class_Data的架构
              dt.Clear();
              for (int i = 5; i < Excel_dt.Rows.Count; i++)
              {
                  // dr = dt.Rows[i];//获取Excel的当前操作行的数据
                  if (!(Excel_dt.Rows[i][name[0]].ToString() == "周次" || Excel_dt.Rows[i][name[0]].ToString() == ""))
                  {
                      string teachername = Excel_dt.Rows[i][name[4]].ToString(); //获取授课老师列的数据
                      int    k           = Teacher(teachername) + 1;             //判断有多少位老师上同一节课
                      for (int m = 1; m <= k; m++)                               //有几位老师,就循环几次
                      {
                          string teachernamepick;                                //定义截取的老师名字
                          //以逗号为分界点,把多位老师的名字分成各自的名字
                          if ((k == 1) || (m == k))
                          {
                              teachernamepick = teachername;
                          }
                          else
                          {
                              int index2 = teachername.IndexOf(",");
                              teachernamepick = teachername.Substring(0, index2);
                              teachername     = teachername.Remove(0, index2 + 1);
                          }


                          int j;
                          //判断星期几,返回对应的数字
                          switch (Excel_dt.Rows[i][name[1]].ToString().Substring(0, 1))
                          {
                          case "一": j = 1; break;

                          case "二": j = 2; break;

                          case "三": j = 3; break;

                          case "四": j = 4; break;

                          case "五": j = 5; break;

                          default: j = 0; break;
                          }
                          if (teachernamepick != null && teachernamepick != "")
                          {
                              DataRow drClass_information = dt.NewRow();
                              drClass_information["Class_Day"] = j;
                              //获取节次
                              string strclassname  = Excel_dt.Rows[i][name[2]].ToString();
                              int    classnumindex = strclassname.IndexOf("-");
                              drClass_information["Teacher"]       = teachernamepick;
                              drClass_information["Class_ID"]      = teachernamepick + Excel_dt.Rows[i][name[0]].ToString() + j.ToString() + strclassname.Substring(0, classnumindex) + strclassname.Substring(classnumindex + 1) + classname.Substring(5) + Excel_dt.Rows[i][name[3]] + banji;
                              drClass_information["Teacher_ID"]    = "0000000000";
                              drClass_information["Class_Week"]    = Excel_dt.Rows[i][name[0]];
                              drClass_information["Class_Number"]  = Convert.ToInt32(strclassname.Substring(0, classnumindex) + strclassname.Substring(classnumindex + 1));
                              drClass_information["Class_Address"] = Excel_dt.Rows[i][name[3]];
                              drClass_information["Class_Name"]    = classname.Substring(5);
                              drClass_information["Class_Content"] = Excel_dt.Rows[i][name[5]];
                              drClass_information["Class_Type"]    = Excel_dt.Rows[i][name[6]];
                              drClass_information["Spcialty"]      = spcialty;

                              dt.Rows.Add(drClass_information);
                          }
                          else
                          {
                              return(0);
                          }
                      }
                  }
              }
              dtClass.Merge(dt, true);

              daClass.Update(dtClass);
              return(1);
          }catch (Exception) {
              return(0);
          }
      }