Пример #1
1
        public void Load_RowStateUpsertDuplicateKey2()
        {
            localSetup();
            _dt.Rows.Add(new object[] { 4, "mono 4" });
            DataTable dtLoad = new DataTable("LoadRowStateChanges");
            dtLoad.Columns.Add("id", typeof(int));
            dtLoad.Columns.Add("name", typeof(string));
            dtLoad.PrimaryKey = new DataColumn[] { dtLoad.Columns["id"] };
            dtLoad.Rows.Add(new object[] { 1, "RowState 1" });
            dtLoad.Rows.Add(new object[] { 2, "RowState 2" });
            dtLoad.Rows.Add(new object[] { 3, "RowState 3" });
            dtLoad.AcceptChanges();
            dtLoad.Rows[2].Delete();
            DataTableReader dtr = _dt.CreateDataReader();
            dtLoad.Load(dtr, LoadOption.Upsert);
            dtLoad.AcceptChanges();

            try
            {
                Assert.Equal(" ", dtLoad.Rows[4][1]);
                Assert.False(true);
            }
            catch (IndexOutOfRangeException)
            {
            }
        }
Пример #2
1
        public void Load_RowStateUpsertUnpresent()
        {
            localSetup();
            _dt.Rows.Add(new object[] { 4, "mono 4" });
            DataTable dtLoad = new DataTable("LoadRowStateChanges");
            dtLoad.Columns.Add("id", typeof(int));
            dtLoad.Columns.Add("name", typeof(string));
            dtLoad.PrimaryKey = new DataColumn[] { dtLoad.Columns["id"] };
            dtLoad.Rows.Add(new object[] { 1, "RowState 1" });
            dtLoad.Rows.Add(new object[] { 2, "RowState 2" });
            dtLoad.Rows.Add(new object[] { 3, "RowState 3" });
            dtLoad.AcceptChanges();
            DataTableReader dtr = _dt.CreateDataReader();
            dtLoad.Load(dtr, LoadOption.Upsert);

            try
            {
                Assert.Equal(" ", dtLoad.Rows[3][1, DataRowVersion.Original]);
                Assert.False(true);
            }
            catch (VersionNotFoundException)
            {
            }
        }
Пример #3
0
        public DataViewTest()
        {
            _dataTable = new DataTable("itemTable");
            _dc1 = new DataColumn("itemId");
            _dc2 = new DataColumn("itemName");
            _dc3 = new DataColumn("itemPrice");
            _dc4 = new DataColumn("itemCategory");

            _dataTable.Columns.Add(_dc1);
            _dataTable.Columns.Add(_dc2);
            _dataTable.Columns.Add(_dc3);
            _dataTable.Columns.Add(_dc4);
            DataRow dr;
            _seed = 123;
            _rowCount = 5;
            _rndm = new Random(_seed);
            for (int i = 1; i <= _rowCount; i++)
            {
                dr = _dataTable.NewRow();
                dr["itemId"] = "item " + i;
                dr["itemName"] = "name " + _rndm.Next();
                dr["itemPrice"] = "Rs. " + (_rndm.Next() % 1000);
                dr["itemCategory"] = "Cat " + ((_rndm.Next() % 10) + 1);
                _dataTable.Rows.Add(dr);
            }
            _dataTable.AcceptChanges();
            _dataView = new DataView(_dataTable);
            _dataView.ListChanged += new ListChangedEventHandler(OnListChanged);
            _listChangedArgs = null;
        }
Пример #4
0
        public static DataTable CreateChildDataTable()
        {
            DataTable dtChild = new DataTable("Child");
            dtChild.Columns.Add("ParentId", typeof(int));
            dtChild.Columns.Add("ChildId", typeof(int));
            dtChild.Columns.Add("String1", typeof(string));
            dtChild.Columns.Add("String2", typeof(string));
            dtChild.Columns.Add("ChildDateTime", typeof(DateTime));
            dtChild.Columns.Add("ChildDouble", typeof(double));

            dtChild.Rows.Add(new object[] { 1, 1, "1-String1", "1-String2", new DateTime(2000, 1, 1, 0, 0, 0, 0), 1.534 });
            dtChild.Rows.Add(new object[] { 1, 2, "2-String1", "2-String2", DateTime.MaxValue, -1.534 });
            dtChild.Rows.Add(new object[] { 1, 3, "3-String1", "3-String2", DateTime.MinValue, double.MaxValue / 10000 });
            dtChild.Rows.Add(new object[] { 2, 1, "1-String1", "1-String2", new DateTime(1973, 6, 20, 0, 0, 0, 0), double.MinValue * 10000 });
            dtChild.Rows.Add(new object[] { 2, 2, "2-String1", "2-String2", new DateTime(2008, 12, 1, 13, 59, 59, 59), 0.45 });
            dtChild.Rows.Add(new object[] { 2, 3, "3-String1", "3-String2", new DateTime(2003, 1, 1, 1, 1, 1, 1), 0.55 });
            dtChild.Rows.Add(new object[] { 5, 1, "1-String1", "1-String2", new DateTime(2002, 1, 1, 1, 1, 1, 1), 0 });
            dtChild.Rows.Add(new object[] { 5, 2, "2-String1", "2-String2", new DateTime(2001, 1, 1, 1, 1, 1, 1), 10 });
            dtChild.Rows.Add(new object[] { 5, 3, "3-String1", "3-String2", new DateTime(2000, 1, 1, 1, 1, 1, 1), 20 });
            dtChild.Rows.Add(new object[] { 6, 1, "1-String1", "1-String2", new DateTime(2000, 1, 1, 1, 1, 1, 0), 25 });
            dtChild.Rows.Add(new object[] { 6, 2, "2-String1", "2-String2", new DateTime(2000, 1, 1, 1, 1, 0, 0), 30 });
            dtChild.Rows.Add(new object[] { 6, 3, "3-String1", "3-String2", new DateTime(2000, 1, 1, 0, 0, 0, 0), 35 });
            dtChild.AcceptChanges();
            return dtChild;
        }
Пример #5
0
        public void AcceptChanges()
        {
            DataTable myTable = new DataTable("myTable");
            DataRow myRow;
            myRow = myTable.NewRow();
            myTable.Rows.Add(myRow);

            // DataRow AcceptChanges
            // DataRowState.Added -> DataRowState.Unchanged 
            myTable.AcceptChanges();
            Assert.Equal(DataRowState.Unchanged, myRow.RowState);
        }
Пример #6
0
        public DataTableReaderTest()
        {
            _dt = new DataTable("test");
            _dt.Columns.Add("id", typeof(int));
            _dt.Columns.Add("name", typeof(string));
            _dt.PrimaryKey = new DataColumn[] { _dt.Columns["id"] };

            _dt.Rows.Add(new object[] { 1, "mono 1" });
            _dt.Rows.Add(new object[] { 2, "mono 2" });
            _dt.Rows.Add(new object[] { 3, "mono 3" });

            _dt.AcceptChanges();
        }
Пример #7
0
        public void LoadRowTest()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("name", typeof(string));

            dt.Rows.Add(new object[] { 1, "mono 1" });
            dt.Rows.Add(new object[] { 2, "mono 2" });
            dt.Rows.Add(new object[] { 3, "mono 3" });

            dt.PrimaryKey = new DataColumn[] { dt.Columns["id"] };
            dt.AcceptChanges();

            dt.LoadDataRow(new object[] { 4, "mono 4" }, LoadOption.Upsert);
            Assert.Equal(4, dt.Rows.Count);
        }
Пример #8
0
        public static DataTable CreateParentDataTable()
        {
            DataTable dtParent = new DataTable("Parent");

            dtParent.Columns.Add("ParentId", typeof(int));
            dtParent.Columns.Add("String1", typeof(string));
            dtParent.Columns.Add("String2", typeof(string));

            dtParent.Columns.Add("ParentDateTime", typeof(DateTime));
            dtParent.Columns.Add("ParentDouble", typeof(double));
            dtParent.Columns.Add("ParentBool", typeof(bool));

            dtParent.Rows.Add(new object[] { 1, "1-String1", "1-String2", new DateTime(2005, 1, 1, 0, 0, 0, 0), 1.534, true });
            dtParent.Rows.Add(new object[] { 2, "2-String1", "2-String2", new DateTime(2004, 1, 1, 0, 0, 0, 1), -1.534, true });
            dtParent.Rows.Add(new object[] { 3, "3-String1", "3-String2", new DateTime(2003, 1, 1, 0, 0, 1, 0), double.MinValue * 10000, false });
            dtParent.Rows.Add(new object[] { 4, "4-String1", "4-String2", new DateTime(2002, 1, 1, 0, 1, 0, 0), double.MaxValue / 10000, true });
            dtParent.Rows.Add(new object[] { 5, "5-String1", "5-String2", new DateTime(2001, 1, 1, 1, 0, 0, 0), 0.755, true });
            dtParent.Rows.Add(new object[] { 6, "6-String1", "6-String2", new DateTime(2000, 1, 1, 0, 0, 0, 0), 0.001, false });
            dtParent.AcceptChanges();
            return dtParent;
        }
Пример #9
0
        /// <summary>
        /// 取消审批选中的多条生产计划单
        /// </summary>
        public bool CancelApproveProductionSchedule_Multi(DataTable headTable)
        {
            string psNoListStr = "";

            for (int i = 0; i < headTable.Rows.Count; i++)
            {
                if (DataTypeConvert.GetBoolean(headTable.Rows[i]["Select"]))
                {
                    psNoListStr += string.Format("'{0}',", DataTypeConvert.GetString(headTable.Rows[i]["PsNo"]));
                    headTable.Rows[i]["PsState"] = 1;
                }
            }

            psNoListStr = psNoListStr.Substring(0, psNoListStr.Length - 1);
            if (!CheckPSState(headTable, psNoListStr, true, false, true, false))
            {
                return(false);
            }

            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);
                        cmd.CommandText = string.Format("Update PB_ProductionSchedule set PsState={1} where PsNo in ({0})", psNoListStr, 1);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = string.Format("Delete from PB_ProductionScheduleBom where PsNo in ({0})", psNoListStr);
                        cmd.ExecuteNonQuery();

                        DateTime serverTime = BaseSQL.GetServerDateTime();

                        //保存日志到日志表中
                        DataRow[] headRows = headTable.Select("select=1");
                        for (int i = 0; i < headRows.Length; i++)
                        {
                            ////检查是否有下级的入库单
                            //if (CheckApplyWarehouseWarrant(cmd, DataTypeConvert.GetString(orderHeadRows[i]["OrderHeadNo"])))
                            //{
                            //    trans.Rollback();
                            //    headTable.RejectChanges();
                            //    //MessageHandler.ShowMessageBox("采购订单已经有适用的入库单记录,不可以操作。");
                            //    MessageHandler.ShowMessageBox(f.tsmiCgddyj.Text);
                            //    return false;
                            //}

                            string logStr = LogHandler.RecordLog_OperateRow(cmd, "生产计划单", headRows[i], "PsNo", "取消审批", SystemInfo.user.EmpName, serverTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        }

                        trans.Commit();
                        headTable.AcceptChanges();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        headTable.RejectChanges();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Пример #10
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] Files = Directory.GetFiles(textBox1.Text); //Получаем файлы список файлов

            string Alltext = "";                                //Объявляем переменную для текста

            foreach (string myFile in Files)                    //Собираем все файлы в одну переменную
            {
                Alltext = Alltext + File.ReadAllText(myFile);   //Записываем содержимое каждого файла в переменную
            }


            // Если стоит галка переводим всё что будем сравнивать в нижний регистр, чтобы при расчетах избежать разнницы в регистре.
            if (checkBox1.Checked == false)
            {
                Alltext = Alltext.ToLower();//Получаем нижний регистр
            }


            //Разбиваем текст на массив слов
            string[] SplittedWords = Alltext.Split(new char[] { '.', ',', ' ', '-', ';', ':', ')', '(', '–', '!', '?' });
            //Удаляем пустые элементы массива
            string[] Words = SplittedWords.Where(x => x != "").ToArray();

            //Формируем Datatable
            DataTable dt = new DataTable();

            dt.CaseSensitive = true;                //Включаем регистрозависимость
            dt.Columns.Add("word", typeof(string)); //Задаем названия столбцов и типы даннных
            dt.Columns.Add("count", typeof(int));
            dt.Columns.Add("firstsentence", typeof(string));


            int amount = Convert.ToInt32(textBox2.Text); //Получаем кол-во слов которые нам надо учитывать.

            if (amount > 1)                              //Если их больше одного увеличим на единицу - нужно для верности дальнейших расчетов
            {
                amount++;
            }

            string LongWord = "";                                            //Создадим переменную для длинного слова. Оно потербуется если amount (кол-во слов nграммы) больше одного.

            Action action = () => { progressBar1.Maximum = Words.Count(); }; //Записываем в прогресс бар максимальное значение равное кол-ву обрабатываемых слов

            Invoke(action);


            int i = 1;

            foreach (string Word in Words)           //Перебираем массив слов
            {
                backgroundWorker1.ReportProgress(i); //Инкрементируем прогрессбар
                i++;

                if (amount > 1) //Если колво слов больше одного - вычтем один на этой итерации и добавим текущее итерируемое word к LongWord
                {
                    amount   = amount - 1;
                    LongWord = LongWord + " " + Word;
                    LongWord = LongWord.Trim(); //Обрежем пробелы по краям
                }
                else //Если кол - слов не больше 1, значит или мы набрали уже достаточно в Longword, либо вообще был выбрано только одно слово по умолчанию и небыло никакого LongWord :)
                {
                    if (LongWord != "")                                                                          //Если LongWord не пустое, значит было выбрано более одного слова, а LongWord уже наполнился и мы можем приступать к его обработке
                    {
                        if (dt.Select("word = '" + LongWord + "'").Count() < 1)                                  //Проверяем что это слово уже небыло добавлено в таблицу на предыдущих итерациях - проверяем, что выборка из datatable по этому слову выдает 0 строк.
                        {
                            int    Count           = new Regex("\\W" + LongWord + "\\W").Matches(Alltext).Count; //Считаем колво вхождений слова во всем тексте регулярками
                            string Sentencecontext = GetFirstSentence(LongWord, Alltext);                        //Получаем от соответвующего метода предложение в котором было употреблено первый раз данное словосочетание

                            DataRow row = dt.NewRow();                                                           //Добавляем новую строку
                            row["word"]          = LongWord;
                            row["count"]         = Count;
                            row["firstsentence"] = Sentencecontext;
                            dt.Rows.Add(row);
                            dt.AcceptChanges();
                        }
                        LongWord = "";                                 //Обнуляем LongWord
                        amount   = Convert.ToInt32(textBox2.Text) + 1; //Возвращаем amount исходное значение, чтобы ожидать новое соловосочетание на следующих итерациях цикла
                    }
                    else //Если LongWord таки оказалось пустым, значит было выбрано одно слово в качетсве n-граммы
                    if (dt.Select("word = '" + Word + "'").Count() < 1)                                  //Проверяем что это слово уже небыло добавлено в таблицу на предыдущих итерациях - проверяем, что выборка из datatable по этому слову выдает 0 строк.
                    {
                        int    Count           = new Regex("\\W" + Word + "\\W").Matches(Alltext).Count; //Считаем колво вхождений слова во всем тексте регулярками
                        string Sentencecontext = GetFirstSentence(Word, Alltext);                        //Получаем от соответвующего метода предложение в котором было употреблено первый раз данное словосочетание

                        DataRow row = dt.NewRow();                                                       //Добавляем новую строку
                        row["word"]          = Word;
                        row["count"]         = Count;
                        row["firstsentence"] = Sentencecontext;
                        dt.Rows.Add(row);
                        dt.AcceptChanges();
                    }
                }
            }

            //Удаляем из таблицы строки в которых счетчик вхождений равен 0
            foreach (DataRow row in dt.Rows)
            {
                if (Convert.ToInt32(row["count"]) == 0)
                {
                    row.Delete();
                }
            }
            dt.AcceptChanges();

            e.Result = dt;
        }
Пример #11
0
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Text.IndexOf(',') != -1)
            {
                return;
            }
            this.listView1.Items.Clear();
            ListViewItem listViewItem = (ListViewItem)null;
            DataTable    dataTable    = this.supplier.POList.Copy();

            for (int index = 0; index < dataTable.Rows.Count; ++index)
            {
                DataRow row = dataTable.Rows[index];
                if (e.Node.Parent == null)
                {
                    DateTime dateTime = Convert.ToDateTime(row["Fecha de Compra"]);
                    if (e.Node.Text == dateTime.Year.ToString())
                    {
                        listViewItem = new ListViewItem("Orden de Compra #" + row["ID_PO"].ToString(), 1);
                        this.listView1.Items.Add(listViewItem);
                    }
                }
                if (e.Node.Parent != null && e.Node.Text.IndexOf(",") == -1)
                {
                    DateTime dateTime = Convert.ToDateTime(row["Fecha de Compra"]);
                    string   str;
                    switch (dateTime.Month)
                    {
                    case 1:
                        str = "Enero";
                        break;

                    case 2:
                        str = "Febrero";
                        break;

                    case 3:
                        str = "Marzo";
                        break;

                    case 4:
                        str = "Abril";
                        break;

                    case 5:
                        str = "Mayo";
                        break;

                    case 6:
                        str = "Junio";
                        break;

                    case 7:
                        str = "Julio";
                        break;

                    case 8:
                        str = "Agosto";
                        break;

                    case 9:
                        str = "Septiembre";
                        break;

                    case 10:
                        str = "Octubre";
                        break;

                    case 11:
                        str = "Noviembre";
                        break;

                    case 12:
                        str = "Diciembre";
                        break;

                    default:
                        str = "";
                        break;
                    }
                    if (e.Node.Text == str && e.Node.Parent.Text == dateTime.Year.ToString())
                    {
                        listViewItem = new ListViewItem("Orden de Compra #" + row["ID_PO"].ToString(), 1);
                        this.listView1.Items.Add(listViewItem);
                    }
                }
                if (listViewItem != null)
                {
                    listViewItem.ForeColor = Convert.ToBoolean(row["Estado de Pago"]) ? Color.LimeGreen : Color.Tomato;
                    row.Delete();
                    dataTable.AcceptChanges();
                    --index;
                }
            }
            this.listView1.Sorting = SortOrder.Ascending;
        }
Пример #12
0
 public void Load_MissingColsNullable()
 {
     localSetup();
     DataTable dtLoad = new DataTable("LoadMissingCols");
     dtLoad.Columns.Add("id", typeof(int));
     dtLoad.Columns.Add("name", typeof(string));
     dtLoad.Columns.Add("missing", typeof(string));
     dtLoad.Columns["missing"].AllowDBNull = true;
     dtLoad.PrimaryKey = new DataColumn[] { dtLoad.Columns["id"] };
     dtLoad.Rows.Add(new object[] { 4, "mono 4", "miss4" });
     dtLoad.Rows.Add(new object[] { 5, "mono 5", "miss5" });
     dtLoad.Rows.Add(new object[] { 6, "mono 6", "miss6" });
     dtLoad.AcceptChanges();
     DataTableReader dtr = _dt.CreateDataReader();
     dtLoad.Load(dtr);
     Assert.Equal(3, dtLoad.Columns.Count);
     Assert.Equal(6, dtLoad.Rows.Count);
     Assert.Equal(4, dtLoad.Rows[0][0]);
     Assert.Equal("mono 4", dtLoad.Rows[0][1]);
     Assert.Equal("miss4", dtLoad.Rows[0][2]);
     Assert.Equal(5, dtLoad.Rows[1][0]);
     Assert.Equal("mono 5", dtLoad.Rows[1][1]);
     Assert.Equal("miss5", dtLoad.Rows[1][2]);
     Assert.Equal(6, dtLoad.Rows[2][0]);
     Assert.Equal("mono 6", dtLoad.Rows[2][1]);
     Assert.Equal("miss6", dtLoad.Rows[2][2]);
     Assert.Equal(1, dtLoad.Rows[3][0]);
     Assert.Equal("mono 1", dtLoad.Rows[3][1]);
     //Assert.Null (dtLoad.Rows[3][2]);
     Assert.Equal(2, dtLoad.Rows[4][0]);
     Assert.Equal("mono 2", dtLoad.Rows[4][1]);
     //Assert.Null (dtLoad.Rows[4][2]);
     Assert.Equal(3, dtLoad.Rows[5][0]);
     Assert.Equal("mono 3", dtLoad.Rows[5][1]);
     //Assert.Null (dtLoad.Rows[5][2]);
 }
Пример #13
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.Form.DefaultButton = this.SearchByUserName.UniqueID;

            this.UserSearchName.Focus();

            if (this.IsPostBack)
            {
                return;
            }

            this.ViewState["SortNameField"]      = 1;
            this.ViewState["SortRankNameField"]  = 0;
            this.ViewState["SortJoinedField"]    = 0;
            this.ViewState["SortNumPostsField"]  = 0;
            this.ViewState["SortLastVisitField"] = 0;

            this.PageLinks.AddRoot().AddLink(this.GetText("TITLE"));

            //// this.SetSort("Name", true);

            this.UserName.Text    = this.GetText("username");
            this.Rank.Text        = this.GetText("rank");
            this.Joined.Text      = this.GetText("joined");
            this.Posts.Text       = this.GetText("posts");
            this.LastVisitLB.Text = this.GetText("members", "lastvisit");

            using (DataTable dt = this.Get <IDbFunction>().GetAsDataTable(cdb => cdb.group_list(this.PageContext.PageBoardID, null)))
            {
                // add empty item for no filtering
                DataRow newRow = dt.NewRow();
                newRow["Name"]    = this.GetText("ALL");
                newRow["GroupID"] = DBNull.Value;
                dt.Rows.InsertAt(newRow, 0);

                DataRow[] guestRows = dt.Select("Name='Guests'");

                if (guestRows.Length > 0)
                {
                    foreach (DataRow row in guestRows)
                    {
                        row.Delete();
                    }
                }

                // commits the deletes to the table
                dt.AcceptChanges();

                this.Group.DataSource     = dt;
                this.Group.DataTextField  = "Name";
                this.Group.DataValueField = "GroupID";
                this.Group.DataBind();
            }

            this.NumPostDDL.Items.Add(new ListItem(this.GetText("MEMBERS", "NUMPOSTSEQUAL"), "1"));
            this.NumPostDDL.Items.Add(new ListItem(this.GetText("MEMBERS", "NUMPOSTSLESSOREQUAL"), "2"));
            this.NumPostDDL.Items.Add(new ListItem(this.GetText("MEMBERS", "NUMPOSTSMOREOREQUAL"), "3"));

            this.NumPostDDL.DataBind();

            // get list of user ranks for filtering
            using (DataTable dt = this.Get <IDbFunction>().GetAsDataTable(cdb => cdb.rank_list(this.PageContext.PageBoardID, null)))
            {
                // add empty for for no filtering
                DataRow newRow = dt.NewRow();
                newRow["Name"]   = this.GetText("ALL");
                newRow["RankID"] = DBNull.Value;
                dt.Rows.InsertAt(newRow, 0);

                DataRow[] guestRows = dt.Select("Name='Guest'");

                if (guestRows.Length > 0)
                {
                    foreach (DataRow row in guestRows)
                    {
                        row.Delete();
                    }
                }

                // commits the deletes to the table
                dt.AcceptChanges();

                this.Ranks.DataSource     = dt;
                this.Ranks.DataTextField  = "Name";
                this.Ranks.DataValueField = "RankID";
                this.Ranks.DataBind();
            }

            this.BindData();
        }
Пример #14
0
        public virtual void Import_Excel()
        {
            string         strTableName = TABLENAME;
            OpenFileDialog ofdlg        = new OpenFileDialog();

            ofdlg.DefaultExt = "xls";
            ofdlg.Filter     = "*.xls|*.xls";

            if (ofdlg.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            string probeConnStr = @"Provider=Microsoft.Jet.OLEDB.4.0;
						Data Source= "                         + ofdlg.FileName + ";" +
                                  "Extended Properties=\"Excel 8.0;HDR=YES\"";

            using (OleDbConnection probeConn = new OleDbConnection(probeConnStr))
            {
                probeConn.Open();
                string probe = "SELECT * FROM [Sheet1$] " + //Sheet1$A1:A65536
                               "Where Ma_Vt IS NOT NULL AND Gia IS NOT NULL";

                using (OleDbDataAdapter oleDbDapter = new OleDbDataAdapter(probe, probeConn))
                {
                    DataTable tbExcel = new DataTable();
                    oleDbDapter.Fill(tbExcel);

                    DataTable dtStruct  = DataTool.SQLGetDataTable(strTableName, "TOP 0 * ", " 0 = 1", null);
                    DataTable dtStruct2 = dtStruct.Clone();
                    DataRow   drNewRow  = dtStruct.NewRow();
                    dtStruct.Rows.Add(drNewRow);

                    foreach (DataColumn dc in dtStruct2.Columns)
                    {
                        if (dc.DataType.ToString() == "System.Byte[]")
                        {
                            dtStruct.Columns.Remove(dc.ColumnName);
                            dtStruct.AcceptChanges();
                        }
                    }



                    Common.SetDefaultDataRow(ref drNewRow);

                    string strMsg      = (Element.sysLanguage == enuLanguageType.Vietnamese ? "Bạn có muốn ghi đè lên mẫu tin đã tồn tại không ?" : "Do you want to override exists data ?");
                    bool   bIs_Overide = Common.MsgYes_No(strMsg);

                    foreach (DataRow drExcel in tbExcel.Rows)
                    {
                        Common.CopyDataRow(drExcel, drNewRow);
                        drNewRow.AcceptChanges();

                        //if (DataTool.SQLCheckExist(strTableName, new string [] { "","","",""},new object [] {} ))

                        DataTool.SQLUpdate(enuEdit.New, strTableName, ref drNewRow);
                    }
                }
            }

            Common.MsgOk(Languages.GetLanguage("End_Process"));
        }
Пример #15
0
        public void RowState()
        {
            DataTable myTable = new DataTable("myTable");
            DataColumn dc = new DataColumn("Name", typeof(string));
            myTable.Columns.Add(dc);
            DataRow myRow;

            // Create a new DataRow.
            myRow = myTable.NewRow();

            // Detached row.

            // Detached
            Assert.Equal(DataRowState.Detached, myRow.RowState);

            myTable.Rows.Add(myRow);
            // New row.

            // Added
            Assert.Equal(DataRowState.Added, myRow.RowState);

            myTable.AcceptChanges();
            // Unchanged row.

            // Unchanged
            Assert.Equal(DataRowState.Unchanged, myRow.RowState);

            myRow["Name"] = "Scott";
            // Modified row.

            // Modified
            Assert.Equal(DataRowState.Modified, myRow.RowState);

            myRow.Delete();
            // Deleted row.

            // Deleted
            Assert.Equal(DataRowState.Deleted, myRow.RowState);
        }
Пример #16
0
        /// <summary>
        /// 获取XML的数据加载到DataTable中
        /// </summary>
        /// <param name="p_xmlDocument"></param>
        internal void m_mthGetXMLData(XmlDocument p_xmlDocument)
        {
            if (p_xmlDocument == null)
            {
                return;
            }
            XmlNodeList xmlChileNodeList = p_xmlDocument.SelectSingleNode("Sort").ChildNodes;
            DataRow     drTemp           = null;

            foreach (XmlNode objNode in xmlChileNodeList)
            {
                if (objNode.Name == "Item")
                {
                    drTemp = m_dtBaricodeSort.NewRow();
                    foreach (XmlNode node in objNode.ChildNodes)
                    {
                        switch (node.Name)
                        {
                        case "PatientCard":
                            drTemp["PatientCard"] = node.InnerText;
                            break;

                        case "DateTime":
                            try
                            {
                                drTemp["DateTime"] = Convert.ToDateTime(node.InnerText);
                            }
                            catch
                            {
                                continue;
                            }
                            break;

                        case "PatientName":
                            drTemp["PatientName"] = node.InnerText;
                            break;

                        case "PatientSex":
                            drTemp["PatientSex"] = node.InnerText;
                            break;

                        case "PatientAge":
                            drTemp["PatientAge"] = node.InnerText;
                            break;
                        }
                    }
                    m_dtBaricodeSort.Rows.Add(drTemp);
                    m_dtBaricodeSort.AcceptChanges();
                }
            }
            if (m_dtBaricodeSort.Rows.Count > 0)
            {
                DataTable dtResult = m_dtBaricodeSort.Copy();
                DataView  dvTemp   = dtResult.DefaultView;
                dvTemp.Sort = "DateTime asc";
                m_dtBaricodeSort.Rows.Clear();
                m_dtBaricodeSort           = dvTemp.ToTable();
                m_dgBarcodeSort.DataSource = null;
                m_dgBarcodeSort.DataSource = m_dtBaricodeSort;
            }
        }
Пример #17
0
        public static byte[] RenderChart(int projectId, int basePlanSlotId, bool generateDataXml, string styleFilePath, int portionX, int portionY, int itemsPerPage, int pageNumber)
        {
            GanttView gantt = CreateGanttView(projectId, HeaderItemHeight, ItemHeight);

            if (portionY >= 0)
            {
                #region Add data

                #region Load calendar

                int calendarId = -1;
                using (IDataReader reader = Project.GetProject(projectId))
                {
                    if (reader.Read())
                    {
                        calendarId = (int)reader["CalendarId"];
                    }
                }
                if (calendarId > 0)
                {
                    // Load rules by day of week
                    ArrayList days = new ArrayList();
                    for (byte i = 1; i <= 7; i++)
                    {
                        days.Add(i);
                    }
                    using (IDataReader reader = Mediachase.IBN.Business.Calendar.GetListWeekdayHours(calendarId))
                    {
                        while (reader.Read())
                        {
                            byte b = (byte)reader["DayOfWeek"];
                            days.Remove(b);
                        }
                    }
                    foreach (byte b in days)
                    {
                        gantt.CreateDayElement(ConvertDayOfWeek(b), true);
                    }

                    // Load exceptions
                    using (IDataReader reader = Mediachase.IBN.Business.Calendar.GetListExceptionHoursByCalendar(calendarId))
                    {
                        while (reader.Read())
                        {
                            DateTime fromDate = (DateTime)reader["FromDate"];
                            DateTime toDate   = (DateTime)reader["ToDate"];
                            bool     holiday  = (reader["FromTime"] == DBNull.Value && reader["ToTime"] == DBNull.Value);
                            for (DateTime date = fromDate.Date; date <= toDate.Date; date = date.AddDays(1))
                            {
                                gantt.CreateDateElement(date, holiday);
                            }
                        }
                    }
                }

                #endregion

                #region Load base plan

                Dictionary <int, DateTime> basePlanTaskHash = null;
                if (basePlanSlotId > 0)
                {
                    basePlanTaskHash = SpreadSheet.ProjectSpreadSheet.GetTaskHash(projectId, basePlanSlotId);
                }

                #endregion

                List <string> ids = new List <string>();

                #region Load tasks

                DataTable dt = Task.GetListTasksByProjectCollapsedDataTable(projectId);
                dt.AcceptChanges();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];

                    if (dr.RowState != DataRowState.Deleted)
                    {
                        Element spanElement = gantt.CreateSpanElement(null, null, null);

                        int    taskId = (int)dr["TaskId"];
                        string id     = taskId.ToString(CultureInfo.InvariantCulture);
                        ids.Add(id);
                        DateTime start       = (DateTime)dr["StartDate"];
                        bool     isMilestone = (bool)dr["IsMilestone"];
                        bool     isSummary   = (bool)dr["IsSummary"];
                        bool     isCompleted = (bool)dr["IsCompleted"];
                        string   type        = isSummary ? "Summary" : null;
                        string   tag         = isCompleted ? "Completed" : null;

                        if (isMilestone)
                        {
                            DateTime?basePlanDate = null;

                            if (basePlanTaskHash != null && basePlanTaskHash.ContainsKey(taskId))
                            {
                                basePlanDate = basePlanTaskHash[taskId];
                            }

                            AddMilestone(gantt, spanElement, start, basePlanDate, id, tag);
                        }
                        else
                        {
                            AddInterval(dr, gantt, spanElement, "StartDate", "FinishDate", id, type, tag);

                            if (!isSummary)
                            {
                                AddInterval(dr, gantt, spanElement, "ActualStartDate", "ActualFinishDate", null, "Actual", tag);

                                int progress = (int)dr["PercentCompleted"];
                                if (progress > 0)
                                {
                                    DateTime finish   = (DateTime)dr["FinishDate"];
                                    TimeSpan interval = finish - start;
                                    finish = start + new TimeSpan(interval.Ticks * progress / 100);
                                    AddInterval2(gantt, spanElement, start, finish, null, "Progress", tag);
                                }
                            }
                        }
                    }
                }

                #endregion

                #region Load relations

                using (IDataReader reader = Project.GetListTaskLinksByProject(projectId))
                {
                    while (reader.Read())
                    {
                        //string linkId = reader["LinkId"].ToString();
                        string succId = reader["SuccId"].ToString();
                        string predId = reader["PredId"].ToString();

                        if (ids.Contains(succId) && ids.Contains(predId))
                        {
                            gantt.CreateRelationElement(null, null, null, predId, succId);
                        }
                    }
                }

                #endregion

                #endregion
            }

            return(Render(gantt, generateDataXml, styleFilePath, portionX, portionY, PortionWidth, PortionHeight, itemsPerPage, pageNumber));
        }
Пример #18
0
        void HandleMessage(MessageCommon msg)
        {
            switch (msg.message_type)
            {
            case MessageCommon.FantasyFighterMessage.ChangeWeapon:
            {
                FantasyFighterWeapon Msg = (FantasyFighterWeapon)msg;
                if (Msg.id == Guid.Empty)
                {
                }
                else
                {
                    FighterState fighter = arena.GetFighter(Msg.id);
                    if (fighter != null)
                    {
                        fighter.weapon = Msg.weapon;
                    }
                }
            }
            break;

            case MessageCommon.FantasyFighterMessage.ChangeStance:
            {
                FantasyFighterStance Msg = (FantasyFighterStance)msg;
                if (Msg.id == Guid.Empty)
                {
                }
                else
                {
                    FighterState fighter = arena.GetFighter(Msg.id);
                    if (fighter != null)
                    {
                        fighter.stance = Msg.stance;
                    }
                }
            }
            break;

            case MessageCommon.FantasyFighterMessage.ArenaList:
            {
                FantasyArenaList list = (FantasyArenaList)msg;
                ArenaTable.Rows.Clear();
                foreach (String s in list.arenas)
                {
                    DataRow row = ArenaTable.NewRow();
                    row["name"] = s;
                    ArenaTable.Rows.Add(row);
                }
                ArenaTable.AcceptChanges();
            }
            break;

            case MessageCommon.FantasyFighterMessage.ArenaAdded:
            {
                FantasyArenaAdded list = (FantasyArenaAdded)msg;

                DataRow row = ArenaTable.NewRow();
                row["name"] = list.arenas;
                ArenaTable.Rows.Add(row);

                ArenaTable.AcceptChanges();
            }
            break;

            case MessageCommon.FantasyFighterMessage.ArenaJoined:
            {
                FantasyArenaJoined list = (FantasyArenaJoined)msg;
                arena = new FantasyArena();

                new Arena(this).Show();
            }
            break;
            }
        }
Пример #19
0
        public void bindData()
        {
            Application.DoEvents();

            try
            {
                wnDm      wDm = new wnDm();
                DataTable dt  = null;
                dt = fn_원자재입고식별표_List();

                adoPrt = new DataTable();
                adoPrt = dt.Copy();

                int j = 0;
                int k = 0;

                for (int i = 0; i < this.inputRmGrid.Rows.Count; i++)
                {
                    if ((bool)inputRmGrid.Rows[i].Cells[11].Value == true)  //--- 11= 확인 체크필드
                    {
                        k = 1;
                        string sDate = "" + this.inputRmGrid.Rows[i].Cells[0].Value.ToString();   //입고일자
                        string sNUm  = "" + this.inputRmGrid.Rows[i].Cells[1].Value.ToString();   //입고번호
                        //string sSeq = "" + this.inputRmGrid.Rows[i].Cells[2].Value.ToString();    //입고순번
                        string sName = "" + this.inputRmGrid.Rows[i].Cells[2].Value.ToString();   //원자재명
                        string sSpec = "" + this.inputRmGrid.Rows[i].Cells[3].Value.ToString();   //규격
                        string sUnit = "" + this.inputRmGrid.Rows[i].Cells[4].Value.ToString();   //단위
                        //string sODate = "" + this.inputRmGrid.Rows[i].Cells[1].Value.ToString();    //주문일자
                        //string sONUm = "" + this.inputRmGrid.Rows[i].Cells[2].Value.ToString();    //주문번호
                        //string sOSeq = "" + this.inputRmGrid.Rows[i].Cells[2].Value.ToString();    //주문순번

                        string nQty  = "" + decimal.Parse(this.inputRmGrid.Rows[i].Cells[5].Value.ToString().Trim()).ToString("#,0.######"); //수량
                        string nCost = "" + this.inputRmGrid.Rows[i].Cells[6].Value.ToString().Trim();                                       //단가
                        string nAmt  = "" + this.inputRmGrid.Rows[i].Cells[7].Value.ToString().Trim();                                       //금액

                        string sHeat = "" + this.inputRmGrid.Rows[i].Cells[8].Value.ToString();                                              //heat no
                        //string sHeatTime = "" + this.inputRmGrid.Rows[i].Cells[6].Value.ToString();    //heat no
                        string sCode  = "" + this.inputRmGrid.Rows[i].Cells[9].Value.ToString();                                             //원자재코드
                        string sUcode = "" + this.inputRmGrid.Rows[i].Cells[10].Value.ToString();                                            //단위코드

                        //string sIsbn = "*" + this.inputRmGrid.Rows[i].Cells[5].Value.ToString() + "*";    //단위

                        string sLotno  = "" + this.inputRmGrid.Rows[i].Cells[12].Value.ToString(); //lot no
                        string sCustcd = "" + this.inputRmGrid.Rows[i].Cells[13].Value.ToString(); //cust_cd
                        string sCustnm = "" + this.inputRmGrid.Rows[i].Cells[14].Value.ToString(); //cust_nm

                        sNUm = sLotno.Substring(0, 12);                                            //--- 입고번호 = 입고일자+번호(yyyyMMdd0000)

                        dt.Rows[j]["no"] = j;

                        dt.Rows[j]["입고일자"]          = sDate;
                        dt.Rows[j]["입고번호"]          = sNUm;
                        dt.Rows[j]["입고순번"]          = "";
                        dt.Rows[j]["원자재코드"]         = sCode;
                        dt.Rows[j]["원자재명"]          = sName;
                        dt.Rows[j]["규격"]            = sSpec;
                        dt.Rows[j]["HEAT_NO"]       = sHeat;
                        dt.Rows[j]["HEAT_TIME"]     = "";
                        dt.Rows[j]["ORDER_DATE"]    = "";
                        dt.Rows[j]["ORDER_CD"]      = "";
                        dt.Rows[j]["ORDER_SEQ"]     = "";
                        dt.Rows[j]["RAW_MAT_GUBUN"] = "";
                        dt.Rows[j]["S_CODE_NM"]     = "";
                        dt.Rows[j]["단위코드"]          = sUcode;
                        dt.Rows[j]["단위명"]           = sUnit;
                        dt.Rows[j]["수량"]            = nQty;
                        dt.Rows[j]["단가"]            = nCost;
                        dt.Rows[j]["금액"]            = nAmt;
                        dt.Rows[j]["제조번호"]          = sLotno;
                        dt.Rows[j]["바코드제조번호"]       = "*" + sLotno + "*";
                        dt.Rows[j]["제조번호"]          = sLotno;
                        dt.Rows[j]["공급처"]           = sCustnm;

                        j = j + 1;

                        adoPrt = dt.Copy();
                    }
                }

                //데이타 끝나고 다시 copy를 써준 이유는 for중에 no에 값을 엏었기 때문에 출력물 데이타테이블(dt)를 다시 복사함
                adoPrt = dt.Copy();

                //for (int i = j; i < this.inputRmGrid.Rows.Count; i++)
                //{
                //    adoPrt.Rows[i].Delete();
                //}
                for (int i = 0; i < adoPrt.Rows.Count; i++)
                {
                    if (adoPrt.Rows[i]["no"] == null || adoPrt.Rows[i]["no"].ToString().Equals(""))
                    {
                        adoPrt.Rows[i].Delete();
                    }
                }
                adoPrt.AcceptChanges(); //--삭제확정

                if (k == 0)
                {
                    strCondition = "No";
                }
            }
            catch (Exception ex)
            {
                strCondition = "ERROR";
                MessageBox.Show("검색중에 오류가 발생했습니다.");
                wnLog.writeLog(wnLog.LOG_ERROR, ex.Message + " - " + ex.ToString());
                Popup.pop오류리포트 msg = new Popup.pop오류리포트(ex.Message + " - " + ex.ToString());
                msg.ShowDialog();
            }
        }
Пример #20
0
        private void DoSave()
        {
            string      strField  = string.Empty;
            string      strValues = string.Empty;
            TabPageEdit tab       = tabs[xtabItemInfo.SelectedTabPageIndex];
            int         iFocu     = tab.GridViewEdit.FocusedRowHandle;

            tab.GridViewEdit.FocusedRowHandle = -1;
            tab.GridViewEdit.FocusedRowHandle = iFocu;
            DataTable dtInfo = (tab.GridViewEdit.GridControl.DataSource as DataView).Table;

            if (dtInfo.GetChanges() == null)
            {
                return;
            }
            foreach (DataRow dr in dtInfo.Rows)
            {
                if (dr.RowState == DataRowState.Added)
                {
                    strValues = StaticFunctions.GetAddValues(dr, tab.StrFileds, out strField);
                    List <string> lisSpParmValue = new List <string>();
                    string[]      strKey         = "ClassType,strFields,strFieldValues,EUser_Id,EDept_Id,Fy_Id,flag".Split(",".ToCharArray());
                    lisSpParmValue.AddRange(new string[] { strClassType,
                                                           strField,
                                                           strValues,
                                                           CApplication.App.CurrentSession.UserId.ToString(),
                                                           CApplication.App.CurrentSession.DeptId.ToString(),
                                                           CApplication.App.CurrentSession.FyId.ToString(),
                                                           tab.AddFlag });
                    DataSet dtAdd = this.DataRequest_By_DataSet(strSpName, strKey, lisSpParmValue.ToArray());
                    if (dtAdd == null)
                    {
                        return;
                    }
                    DataRow drNew = dtAdd.Tables[0].Rows[0];
                    dr[tab.StrKeyId] = drNew[tab.StrKeyId];
                }
                else if (dr.RowState == DataRowState.Modified)
                {
                    strValues = StaticFunctions.GetUpdateValues(dtInfo, dr, tab.StrFileds);
                    if (strValues == string.Empty)
                    {
                        continue;
                    }

                    List <string> lisSpParmValue = new List <string>();
                    string[]      strKey         = "strEditSql,Key_Id,EUser_Id,EDept_Id,Fy_Id,flag".Split(",".ToCharArray());
                    lisSpParmValue.AddRange(new string[] {
                        strValues,
                        dr[tab.StrKeyId].ToString(),
                        CApplication.App.CurrentSession.UserId.ToString(),
                        CApplication.App.CurrentSession.DeptId.ToString(),
                        CApplication.App.CurrentSession.FyId.ToString(),
                        tab.EditFlag
                    });
                    DataTable dtAdd = this.DataRequest_By_DataTable(strSpName, strKey, lisSpParmValue.ToArray());
                    if (dtAdd == null)
                    {
                        return;
                    }
                }
            }
            dtInfo.AcceptChanges();
            MessageBox.Show("操作完成.");
        }
Пример #21
0
        /// <summary>
        /// Description: Fill DataSet with Actual Values which needs to be send on DB
        /// </summary>
        /// <param name="oEntity"></param>
        /// <returns>Convert oEntity to DataSet which contains data in DataTable collection format</returns>
        public DataSet FillEntityWithValues(MasterEntity oEntity)
        {
            DataSet   DTSet         = new MasterEntity().GetTablesStructure();
            DataTable DTMasterTable = DTSet.Tables[MasterEntity.DBTableAndType.TABLE_LoggedInUserDetails];
            DataTable DT_LOGGEDINUSERDETAILS_COMMONSEARCH = DTSet.Tables[MasterEntity.DBTableAndType.TABLE_LoggedInUserDetails_CommonSearch];

            DataRow dr = DTMasterTable.NewRow();

            try
            {
                if (oEntity.LoggedInUserID != null)
                {
                    dr[MasterEntityFields.LOGGEDINUSERID] = oEntity.LoggedInUserID;
                }

                if (oEntity.UserName != null)
                {
                    dr[MasterEntityFields.USERNAME] = oEntity.UserName;
                }

                if (oEntity.IsLoggedInNow != null)
                {
                    dr[MasterEntityFields.ISLOGGEDINNOW] = oEntity.IsLoggedInNow;
                }

                if (oEntity.LoggedInFromDomain != null)
                {
                    dr[MasterEntityFields.LOGGEDINFROMDOMAIN] = oEntity.LoggedInFromDomain;
                }

                if (oEntity.LoggedInAt != null)
                {
                    dr[MasterEntityFields.LOGGEDINAT] = oEntity.LoggedInAt;
                }

                if (oEntity.LoggedInFromIP != null)
                {
                    dr[MasterEntityFields.LOGGEDINFROMIP] = oEntity.LoggedInFromIP;
                }

                if (oEntity.LoggedInUserAgent != null)
                {
                    dr[MasterEntityFields.LOGGEDINUSERAGENT] = oEntity.LoggedInUserAgent;
                }

                DTMasterTable.Rows.Add(dr);
                DTMasterTable.AcceptChanges();

                // Collect the information from oEntity LoggedInUserDetails_CommonSearch and fill the data in DT_LOGGEDINUSERDETAILS_COMMONSEARCH DataTable
                if (oEntity.LoggedInUserDetails_CommonSearchList != null)
                {
                    foreach (ChildLoggedInUserDetails_CommonSearchEntity oEntity_ in oEntity.LoggedInUserDetails_CommonSearchList)
                    {
                        //Initialize New row with DataTable
                        dr = DT_LOGGEDINUSERDETAILS_COMMONSEARCH.NewRow();

                        if (oEntity_.UserName != null)
                        {
                            dr[ChildLoggedInUserDetails_CommonSearchEntityFields.USERNAME] = oEntity_.UserName;
                        }

                        if (oEntity_.LoggedInFromDomain != null)
                        {
                            dr[ChildLoggedInUserDetails_CommonSearchEntityFields.LOGGEDINFROMDOMAIN] = oEntity_.LoggedInFromDomain;
                        }

                        //Add Row into DataTable
                        DT_LOGGEDINUSERDETAILS_COMMONSEARCH.Rows.Add(dr);
                    }

                    // Save State of DataTable with Currently filled Data
                    DT_LOGGEDINUSERDETAILS_COMMONSEARCH.AcceptChanges();
                }
            }
            catch (Exception exe)
            {
                throw exe;
            }
            return(DTSet);
        }
Пример #22
0
        private void update_table()
        {
            dataWorker = sql;
            DataRow   selectedDataRow = ((DataRowView)comboBox1.SelectedItem).Row;
            int       Id       = Convert.ToInt32(selectedDataRow["Id"]);
            DataTable groupsRN = MakeGroupsTable();

            string [] fff =
                arrayOtdelGroup(Id);
            if (dataWorker != null)
            {
                //if (Convert.ToInt32(arrayOtdelGroup(Id)[0]) == Id && arrayOtdelGroup(Id).Length> 1)
                if (fff[0] != "")
                {
                    if (Convert.ToInt32(fff[0]) == Id && fff.Length > 1)
                    {
                        for (int i = 0; i < fff.Length; i++)
                        {
                            dataWorker = sql;
                            if (Convert.ToInt32(fff[i]) == 6)
                            {
                                dataWorker = sqlVVO;
                            }
                            ArrayList groups = dataWorker.GetGroups(Convert.ToInt32(fff[i]));
                            foreach (Group group in groups)
                            {
                                groupRow          = groupsRN.NewRow();
                                groupRow["id"]    = group.Id;
                                groupRow["cname"] = group.Name;
                                groupRow["dep"]   = Convert.ToInt32(fff[i]);
                                groupRow["gcn"]   = group.Id;
                                groupsRN.Rows.Add(groupRow);
                            }

                            string    tmpstr           = "";
                            string    nameotdel        = "";
                            string    idotdel          = "";
                            DataTable dtGroupDataTable = sql.getGroupGroup(Convert.ToInt32(fff[i]));
                            foreach (DataRow row in dtGroupDataTable.Rows)
                            {
                                nameotdel = "";
                                idotdel   = "";
                                tmpstr    = Convert.ToString(row["val"]);

                                string[] split = tmpstr.Split(new Char[] { ',', '\t', '\n' });
                                for (int j = 0; j < split.Length; j++)
                                {
                                    //  Console.WriteLine(split[i]);
                                    foreach (DataRow f in groupsRN.Rows)
                                    {
                                        if (split[j] == f["id"].ToString())
                                        {
                                            //f["chk"] = true;
                                            nameotdel += f["cname"] + "/";
                                            idotdel   += f["id"] + "/";
                                            f.Delete();
                                            break;
                                        }
                                    }
                                    groupsRN.AcceptChanges();
                                }
                                //MessageBox.Show(nameotdel);
                                nameotdel = nameotdel.Remove(nameotdel.Length - 1, 1);
                                idotdel   = idotdel.Remove(idotdel.Length - 1, 1);
                                DataRow otdelrow = groupsRN.NewRow();
                                otdelrow["id"]    = Convert.ToInt16(split[0]);
                                otdelrow["cname"] = nameotdel;
                                otdelrow["dep"]   = Convert.ToInt32(fff[i]);
                                otdelrow["gcn"]   = idotdel;
                                // otdelrow["chk"] = true;
                                groupsRN.Rows.InsertAt(otdelrow, Convert.ToInt32(split[0]) - 1);
                                groupsRN.AcceptChanges();
                                groupsRN.DefaultView.Sort = "id asc";
                                groupsRN = groupsRN.DefaultView.ToTable(true);
                            }
                        }
                        //dataGridView1.DataSource = groupsRN;
                    }
                    else
                    {
                        ArrayList groups = dataWorker.GetGroups(Id);
                        foreach (Group group in groups)
                        {
                            groupRow          = groupsRN.NewRow();
                            groupRow["id"]    = group.Id;
                            groupRow["cname"] = group.Name;
                            groupRow["dep"]   = Id;
                            groupRow["gcn"]   = group.Id;
                            groupsRN.Rows.Add(groupRow);
                        }
                        string    tmpstr           = "";
                        string    nameotdel        = "";
                        string    idotdel          = "";
                        DataTable dtGroupDataTable = sql.getGroupGroup(Id);
                        foreach (DataRow row in dtGroupDataTable.Rows)
                        {
                            nameotdel = "";
                            idotdel   = "";
                            tmpstr    = Convert.ToString(row["val"]);

                            string[] split = tmpstr.Split(new Char[] { ',', '\t', '\n' });
                            for (int j = 0; j < split.Length; j++)
                            {
                                Console.WriteLine(split[j]);
                                foreach (DataRow f in groupsRN.Rows)
                                {
                                    if (split[j] == f["id"].ToString())
                                    {
                                        //f["chk"] = true;
                                        nameotdel += f["cname"] + "/";
                                        idotdel   += f["id"] + "/";
                                        f.Delete();
                                        break;
                                    }
                                }
                                groupsRN.AcceptChanges();
                            }
                            //MessageBox.Show(nameotdel);
                            nameotdel = nameotdel.Remove(nameotdel.Length - 1, 1);
                            idotdel   = idotdel.Remove(idotdel.Length - 1, 1);
                            DataRow otdelrow = groupsRN.NewRow();
                            otdelrow["id"]    = Convert.ToInt16(split[0]);
                            otdelrow["cname"] = nameotdel;
                            otdelrow["dep"]   = Id;
                            otdelrow["gcn"]   = idotdel;
                            // otdelrow["chk"] = true;
                            groupsRN.Rows.InsertAt(otdelrow, Convert.ToInt32(split[0]) - 1);
                            groupsRN.AcceptChanges();
                            groupsRN.DefaultView.Sort = "id asc";
                            groupsRN = groupsRN.DefaultView.ToTable(true);
                        }
                    }
                }
                else
                {
                    ArrayList groups = dataWorker.GetGroups(Id);
                    foreach (Group group in groups)
                    {
                        groupRow          = groupsRN.NewRow();
                        groupRow["id"]    = group.Id;
                        groupRow["cname"] = group.Name;
                        groupRow["dep"]   = Id;
                        groupRow["gcn"]   = group.Id;
                        groupsRN.Rows.Add(groupRow);
                    }
                    string    tmpstr           = "";
                    string    nameotdel        = "";
                    string    idotdel          = "";
                    DataTable dtGroupDataTable = sql.getGroupGroup(Id);
                    foreach (DataRow row in dtGroupDataTable.Rows)
                    {
                        nameotdel = "";
                        idotdel   = "";
                        tmpstr    = Convert.ToString(row["val"]);

                        string[] split = tmpstr.Split(new Char[] { ',', '\t', '\n' });
                        for (int j = 0; j < split.Length; j++)
                        {
                            Console.WriteLine(split[j]);
                            foreach (DataRow f in groupsRN.Rows)
                            {
                                if (split[j] == f["id"].ToString())
                                {
                                    //f["chk"] = true;
                                    nameotdel += f["cname"] + "/";
                                    idotdel   += f["id"] + "/";
                                    f.Delete();
                                    break;
                                }
                            }
                            groupsRN.AcceptChanges();
                        }
                        //MessageBox.Show(nameotdel);
                        nameotdel = nameotdel.Remove(nameotdel.Length - 1, 1);
                        idotdel   = idotdel.Remove(idotdel.Length - 1, 1);
                        DataRow otdelrow = groupsRN.NewRow();
                        otdelrow["id"]    = Convert.ToInt16(split[0]);
                        otdelrow["cname"] = nameotdel;
                        otdelrow["dep"]   = Id;
                        otdelrow["gcn"]   = idotdel;
                        // otdelrow["chk"] = true;
                        groupsRN.Rows.InsertAt(otdelrow, Convert.ToInt32(split[0]) - 1);
                        groupsRN.AcceptChanges();
                        groupsRN.DefaultView.Sort = "id asc";
                        groupsRN = groupsRN.DefaultView.ToTable(true);
                    }
                }
                dataGridView1.DataSource = groupsRN;
            }
        }
Пример #23
0
        public void Item()
        {
            // init table with columns
            DataTable myTable = new DataTable("myTable");

            myTable.Columns.Add(new DataColumn("Id", typeof(int)));
            myTable.Columns.Add(new DataColumn("Name", typeof(string)));
            DataColumn dc = myTable.Columns[0];

            myTable.Rows.Add(new object[] { 1, "Ofer" });
            myTable.Rows.Add(new object[] { 2, "Ofer" });

            myTable.AcceptChanges();

            DataRow myRow = myTable.Rows[0];

            //Start checking

            // Item - index
            Assert.Equal(1, (int)myRow[0]);

            // Item - string
            Assert.Equal(1, (int)myRow["Id"]);

            // Item - Column
            Assert.Equal(1, (int)myRow[dc]);

            // Item - index,Current
            Assert.Equal(1, (int)myRow[0, DataRowVersion.Current]);

            // Item - string,Current
            Assert.Equal(1, (int)myRow["Id", DataRowVersion.Current]);

            // Item - columnn,Current
            Assert.Equal(1, (int)myRow[dc, DataRowVersion.Current]);

            //	testMore();
        }
Пример #24
0
    private void GetOpenMatch()
    {
        DateTime BeginTime = Shove._Convert.StrToDateTime(tbBeginTime.Text, DateTime.Now.AddDays(-3).ToString());
        DateTime EndTime   = Shove._Convert.StrToDateTime(tbEndTime.Text, DateTime.Now.ToString()).AddDays(1);

        string Key = "Open_kj_lanq_GetOpenMatch" + BeginTime.ToString("yyyy-MM-dd") + EndTime.ToString("yyyy-MM-dd");

        DataTable dt = Shove._Web.Cache.GetCacheAsDataTable(Key);

        if (dt == null)
        {
            string strCmd = @"select ROW_NUMBER() OVER (ORDER BY StopSellingTime desc, MatchNumber desc) AS id, StopSellingTime, MatchNumber, Game, MainTeam, GuestTeam, 
                                isnull(Givewinlosescore, 0) as MainLoseBall, DXResult, DXBonus, RFSFResult, RFSFBonus, SFResult, SFBonus, SFCResult, SFCBonus, Result
                                from T_MatchBasket
                                where StopSellingTime between '" + BeginTime.ToString("yyyy-MM-dd") + "' and '" + EndTime.ToString("yyyy-MM-dd") + "' and isnull(Result, '') <> '' order by  StopSellingTime, MatchNumber desc";

            dt = MSSQL.Select(strCmd);

            if (dt == null)
            {
                PF.GoError(ErrorNumber.DataReadWrite, "数据库繁忙,请重试", this.GetType().BaseType.FullName);

                return;
            }

            if (dt.Rows.Count > 0)
            {
                Shove._Web.Cache.SetCache(Key, dt, 600);
            }
        }

        DataTable dtGame = new DataTable();

        dtGame.Columns.Add("Game", typeof(System.String));
        DataRow drGame = dtGame.NewRow();

        drGame["Game"] = "全部联赛";

        dtGame.Rows.Add(drGame);
        dtGame.AcceptChanges();

        object LastValue = null;

        foreach (DataRow dr in dt.Select("", "Game"))
        {
            if (LastValue == null || !(ColumnEqual(LastValue, dr["Game"])))
            {
                LastValue = dr["Game"];

                DataRow drGame1 = dtGame.NewRow();
                drGame1["Game"] = dr["Game"].ToString();
                dtGame.Rows.Add(drGame1);
                dtGame.AcceptChanges();
            }
        }

        Shove.ControlExt.FillDropDownList(ddlleague, dtGame, "Game", "Game");

        int    SumPage = dt.Rows.Count;
        string league  = Shove._Web.Utility.GetRequest("league");

        if (league != "" && league != "全部联赛")
        {
            SumPage = dt.Select("Game='" + league + "'").Length;
        }

        int Count = Shove._Convert.StrToInt(Shove._Web.Utility.GetRequest("p"), 1);
        int Last  = SumPage % 20 == 0 ? SumPage / 20 : SumPage / 20 + 1;

        string URL = "?";

        if (!string.IsNullOrEmpty(Shove._Web.Utility.GetRequest("startdate")))
        {
            URL += "startdate=" + Shove._Web.Utility.GetRequest("startdate") + "&";
        }

        if (!string.IsNullOrEmpty(Shove._Web.Utility.GetRequest("enddate")))
        {
            URL += "enddate=" + Shove._Web.Utility.GetRequest("enddate") + "&";
        }

        if (!string.IsNullOrEmpty(league))
        {
            URL += "league=" + league + "&";
        }

        lbNum.Text = SumPage.ToString();

        lbPage.Text  = "<li class=\"first\"><a href='" + URL + "p=1'>首页</a></li>";
        lbPage.Text += "<li class=\"previous\"><a href='" + URL + "p=" + (Count == 1 ? "1" : (Count - 1).ToString()) + "'>上一页</a></li>";

        for (int i = 1; i < Last + 1; i++)
        {
            lbPage.Text += (Count == i ? "<li class=\"slect_r\">" + i.ToString() + "</li>" : "<li><a href=\"" + URL + "p=" + i.ToString() + "\">" + i.ToString() + "</a></li>");
        }

        lbPage.Text += "<li class='next'><a href='" + URL + "p=" + (Count == Last ? Last.ToString() : (Count + 1).ToString()) + "'>下一页</a></li>";
        lbPage.Text += "<li class='last'><a href='" + URL + "p=" + Last.ToString() + "'>末页</a></li>";
        lbPage.Text += "<li class='totel'>共" + Last.ToString() + "页</li>";

        DataRow[] drs = dt.Select("1=1", "id");

        if (league != "" && league != "全部联赛")
        {
            drs = dt.Select("Game='" + league + "'");
        }

        string lineStyle = "";

        JczqMatch.Text  = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"data_tablebox\">";
        JczqMatch.Text += "<tr class=\"trt3\"><th width=\"70\" rowspan=\"2\">赛事日期</th>";
        JczqMatch.Text += "<th width=\"70\" rowspan=\"2\">赛事编号</th>";
        JczqMatch.Text += "<th width=\"70\" rowspan=\"2\">赛事类型</th>";
        JczqMatch.Text += "<th rowspan=\"2\" style=\"width:120px;\">客队 VS 主队</th>";
        JczqMatch.Text += "<th rowspan=\"2\">让分</th>";
        JczqMatch.Text += "<th height=\"24\" colspan=\"2\" class=\"tbottom\">胜负</th>";
        JczqMatch.Text += "<th colspan=\"2\" class=\"tbottom\">让分胜负</th>";
        JczqMatch.Text += "<th colspan=\"2\" class=\"tbottom\">胜分差</th>";
        JczqMatch.Text += "<th colspan=\"2\" class=\"tbottom\">大小分</th></tr>";
        JczqMatch.Text += "<tr class=\"trt4\"><th width=\"35\" height=\"24\">彩果</th>";
        JczqMatch.Text += "<th>奖金</th>";
        JczqMatch.Text += "<th>彩果</th>";
        JczqMatch.Text += "<th>奖金</th>";
        JczqMatch.Text += "<th>彩果</th>";
        JczqMatch.Text += "<th>奖金</th>";
        JczqMatch.Text += "<th>彩果</th>";
        JczqMatch.Text += "<th>奖金</th></tr>";

        for (int i = (Count - 1) * 20; i < (Count * 20 < drs.Length ? Count * 20 : drs.Length); i++)
        {
            DataRow dr = drs[i];

            lineStyle = Shove._Convert.StrToInt(dr["ID"].ToString(), 0) % 2 == 0 ? "tr1" : "tr2";

            JczqMatch.Text += "<tr class=\"" + lineStyle + "\"><td>" + Shove._Convert.StrToDateTime(dr["StopSellingTime"].ToString(), DateTime.Now.ToString()).ToString("yyyy-MM-dd") + "</td>";
            JczqMatch.Text += "<td>" + dr["MatchNumber"].ToString() + "</td>";
            JczqMatch.Text += "<td bgcolor=\"#FF0000\"><span style=\"color:white\">" + dr["Game"].ToString() + "</td>";
            JczqMatch.Text += "<td><div class=\"duizhen\" style=\"width:120px;\"><span>" + dr["GuestTeam"].ToString() + "</span><span style=\"color:red;\">" + dr["Result"].ToString() + "</span> <span>" + dr["MainTeam"].ToString() + "</span></div></td>";
            JczqMatch.Text += "<td><span class=\"" + (Shove._Convert.StrToInt(dr["MainLoseBall"].ToString(), 0) > 0 ? "bred" : "green") + "\">" + dr["MainLoseBall"].ToString() + "</span></td>";
            JczqMatch.Text += "<td>" + dr["SFResult"].ToString() + "</td>";
            JczqMatch.Text += "<td>" + dr["SFBonus"].ToString() + "</td>";
            JczqMatch.Text += "<td>" + dr["RFSFResult"].ToString() + "</td>";
            JczqMatch.Text += "<td>" + dr["RFSFBonus"].ToString() + "</td>";
            JczqMatch.Text += "<td>" + dr["SFCResult"].ToString() + "</td>";
            JczqMatch.Text += "<td>" + dr["SFCBonus"].ToString() + "</td>";
            JczqMatch.Text += "<td>" + dr["DXResult"].ToString() + "</td>";
            JczqMatch.Text += "<td>" + dr["DXBonus"].ToString() + "</td></tr>";
        }

        if (league != "" && league != "全部联赛")
        {
            ddlleague.SelectedValue = league;
        }

        JczqMatch.Text += "</table>";
    }
Пример #25
0
        public void setModified_testRollback()
        {
            DataTable table = new DataTable();
            table.Columns.Add("col1", typeof(int));
            table.Columns.Add("col2", typeof(int));

            DataRow row = table.Rows.Add(new object[] { 1, 1 });
            table.AcceptChanges();

            row.SetModified();
            Assert.Equal(row.RowState, DataRowState.Modified);
            Assert.Equal(1, row[0, DataRowVersion.Current]);
            Assert.Equal(1, row[0, DataRowVersion.Original]);
            table.RejectChanges();
            Assert.Equal(row.RowState, DataRowState.Unchanged);
        }
Пример #26
0
        // Import Of PriceList
        private void ImportingOfPriceList(DataTable PriceList, int IDOfReception)
        {
            //
            // Converting UInt32 In Int32
            //
            PriceList.Columns.Add("ID_PH2", typeof(Int32));
            PriceList.Columns.Add("ID_PR2", typeof(Int32));
            //
            foreach (DataRow CurrentRow in PriceList.Rows)
            {
                //
                try
                {
                    CurrentRow["ID_PH2"] = Convert.ToInt32(CurrentRow["ID_PH"]);
                    CurrentRow["ID_PR2"] = Convert.ToInt32(CurrentRow["ID_PR"]);
                }
                catch { this.RecordingInLogFile("Ошибка при конвертации ID_PH and ID_PR"); }
            }
            //
            try
            {
                if (PriceList.PrimaryKey.Length != 0)
                {
                    PriceList.PrimaryKey = new DataColumn[2] {
                        PriceList.Columns["ID_PH2"], PriceList.Columns["ID_PR2"]
                    }
                }
                ;
            }
            catch { this.RecordingInLogFile("asl"); }
            //
            PriceList.Columns.Remove("ID_PH");
            PriceList.Columns.Remove("ID_PR");
            //
            PriceList.Columns["ID_PH2"].ColumnName = "ID_PH";
            PriceList.Columns["ID_PR2"].ColumnName = "ID_PR";
            //
            // Converting Null And DBNUll in 0
            //
            foreach (DataRow CurrentPrice in PriceList.Rows)
            {
                if ((CurrentPrice["Price"] == null) || (CurrentPrice["Price"] is DBNull))
                {
                    CurrentPrice["Price"] = 0;
                }
            }
            //
            // Getting IDs Of Drugstores
            //
            DataTable TableOfIDsOfDrugstores = new DataView(PriceList).ToTable(true, "ID_PH");

            int[] IDsOfDrugstores = new int[TableOfIDsOfDrugstores.Rows.Count];
            for (int i = 0; i < IDsOfDrugstores.Length; i++)
            {
                IDsOfDrugstores[i] = (int)TableOfIDsOfDrugstores.Rows[i]["ID_PH"];
            }
            //
            // Checking Existence Of Drugstores
            //
            System.Collections.ArrayList CheckedIDs = new System.Collections.ArrayList();
            foreach (int CurrentID in IDsOfDrugstores)
            {
                if (DrugstoreIsActive(CurrentID))
                {
                    CheckedIDs.Add(CurrentID);
                }
            }
            IDsOfDrugstores = new int[0];
            IDsOfDrugstores = (int[])CheckedIDs.ToArray(typeof(int));
            //
            // Recording In Reports Of Importing
            //
            bool Successful = true;

            foreach (int CurrentID in IDsOfDrugstores)
            {
                Successful = RecordingInReportsOfImporting(CurrentID, IDOfReception); if (!Successful)
                {
                    break;
                }
            }
            //
            // Importing Of Drugstores
            //
            //int CountOfImporting = 0;
            DataView GettingDrugstore = new DataView(PriceList);

            for (int i = 0; ((i < IDsOfDrugstores.Length) && Successful); i++)
            {
                //
                // Getting Prices Of Drugstore
                //
                GettingDrugstore.RowFilter = String.Format("ID_PH={0}", IDsOfDrugstores[i]);
                DataTable PricesOfDrugstore = GettingDrugstore.ToTable("PricesOfDrugstore");
                //
                // Addition Of TMP Of ID Of Prices
                //
                PricesOfDrugstore.Columns.Add(new DataColumn("ID", typeof(int)));
                for (int i2 = 0; i2 < PricesOfDrugstore.Rows.Count; i2++)
                {
                    PricesOfDrugstore.Rows[i2]["ID"] = (i2 + 1);
                }
                PricesOfDrugstore.PrimaryKey = new DataColumn[1] {
                    PricesOfDrugstore.Columns["ID"]
                };
                //
                // Filling ID Of Prices And ID_PR Of Products
                //
                int[,] IDAndIDPROfPrices = new int[PricesOfDrugstore.Rows.Count, 2];
                for (int i2 = 0; i2 <= IDAndIDPROfPrices.GetUpperBound(0); i2++)
                {
                    IDAndIDPROfPrices[i2, 0] = (int)PricesOfDrugstore.Rows[i2]["ID"];
                    IDAndIDPROfPrices[i2, 1] = (int)PricesOfDrugstore.Rows[i2]["ID_PR"];
                }
                //
                // Search And Liquidation Of Recurrences
                //
                for (int i2 = 0; i2 <= IDAndIDPROfPrices.GetUpperBound(0); i2++)
                {
                    for (int i3 = 0; i3 <= IDAndIDPROfPrices.GetUpperBound(0); i3++)
                    {
                        if ((i2 != i3) && (i2 > i3) && (IDAndIDPROfPrices[i2, 1] == IDAndIDPROfPrices[i3, 1]))
                        {
                            DataRow GetRow = PricesOfDrugstore.Rows.Find(IDAndIDPROfPrices[i3, 0]);
                            if (GetRow != null)
                            {
                                GetRow.Delete();
                            }
                        }
                    }
                }
                //
                PricesOfDrugstore.AcceptChanges();
                //
                // Getting AllPrices From Drugstore
                //
                bool AllPrices = false;
                for (int i2 = 0; i2 < PricesOfDrugstore.Rows.Count; i2++)
                {
                    if (!(PricesOfDrugstore.Rows[i2]["AllPrices"] is DBNull))
                    {
                        if ((bool)PricesOfDrugstore.Rows[i2]["AllPrices"])
                        {
                            AllPrices = true; break;
                        }
                    }
                }
                //
                // Recording In Reports Of Importing Of PriceList
                //
                UpdatingReportsOfImporting(
                    IDsOfDrugstores[i], IDOfReception, PricesOfDrugstore.Rows.Count, AllPrices);
                //
                // Clearing Columns Of Drugstore
                //
                DataView FilteringOfColumns = new DataView(PricesOfDrugstore);
                PricesOfDrugstore =
                    FilteringOfColumns.ToTable(
                        "PricesOfDrugstore", true, "ID_PR", "Price", "Deleting", "Preferential");
                PricesOfDrugstore.PrimaryKey = new DataColumn[] { PricesOfDrugstore.Columns["ID_PR"] };
                //
                // Importing Of Prices Of Drugstore
                //
                ImportingOfPricesOfDrugstore(IDOfReception, IDsOfDrugstores[i], AllPrices, PricesOfDrugstore);
                //
            }
        }
Пример #27
0
        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtBrowse.Text.Trim().ToString()))
            {
                MessageBox.Show("Please Select Excel File First...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            btnBrowse.Enabled = false;

            if (GRights.Contains("A") || GRights.Contains("U") || GRights.Contains("D"))
            {
                btnImport.Enabled = true;
            }
            else
            {
                btnImport.Enabled = false;
            }



            Cursor.Current      = Cursors.WaitCursor;
            grd_view.DataSource = null;
            string filePath = txtBrowse.Text.ToString();

            string sexcelconnectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
            //string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + filePath + ";extended properties=" + "\"excel 8.0;hdr=yes;IMEX=1;\"";

            OleDbConnection  oledbconn = new OleDbConnection(sexcelconnectionstring);
            List <SheetName> sheets    = ExcelHelper.GetSheetNames(oledbconn);
            string           sheetname = "[" + sheets[0].sheetName.Replace("'", "") + "]";

            try
            {
                oledbconn.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }



            try
            {
                string           myexceldataquery = "select EmpUnqID,SanDate,InTime,OutTime,ShiftCode,TPAHours,'' as Remarks from " + sheetname;
                OleDbDataAdapter oledbda          = new OleDbDataAdapter(myexceldataquery, oledbconn);
                dt.Clear();
                oledbda.Fill(dt);

                dt.AcceptChanges();
                foreach (DataRow row in dt.Rows)
                {
                    if (string.IsNullOrEmpty(row["EmpUnqID"].ToString().Trim()))
                    {
                        row.Delete();
                    }
                }
                dt.AcceptChanges();

                oledbconn.Close();
            }
            catch (Exception ex)
            {
                oledbconn.Close();
                MessageBox.Show("Please Check upload template.." + Environment.NewLine + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor.Current    = Cursors.Default;
                btnImport.Enabled = false;
                oledbconn.Close();
                return;
            }


            DataView dv = dt.DefaultView;

            dv.Sort = "EmpUnqID asc";
            DataTable sortedDT = dv.ToTable();



            grd_view.DataSource = sortedDT;

            if (GRights.Contains("A") || GRights.Contains("U") || GRights.Contains("D"))
            {
                btnImport.Enabled = true;
            }
            else
            {
                btnImport.Enabled = false;
            }

            Cursor.Current = Cursors.Default;
        }
Пример #28
0
        public void LoadPortal(string dni)
        {
            string   flagconteotiempo = "";
            int      hora = 0, minuto = 0, segundo = 0;
            string   factvence = "";
            Conexion con = new Conexion();
            // String BodyHtml = "", HeadHtml = "", FotHtml = "";
            SqlConnection cn = con.conexion();

            cn.Open();
            SqlDataAdapter dap = new SqlDataAdapter("UP_MVE_LISTAPAGEINICIO", cn);
            DataTable      dt  = new DataTable();

            dap.SelectCommand.CommandType = CommandType.StoredProcedure;
            dap.SelectCommand.Parameters.AddWithValue("@Dni", dni);

            dap.Fill(dt);
            cn.Close();

            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string HtmlSeccion = "";

                    string imgBase64 = "";
                    string stittulo  = "";
                    string sdetalle  = "";
                    string rutaimg   = "";
                    // string flagconteotiempo;
                    // int hora, minuto, segundo;



                    stittulo = dt.Rows[i]["c_htmlTit"].ToString();
                    sdetalle = dt.Rows[i]["c_htmlDesc"].ToString();
                    rutaimg  = dt.Rows[i]["c_foto1"].ToString();


                    stittulo = stittulo.ToUpper();
                    sdetalle = sdetalle.ToUpper();

                    flagconteotiempo = dt.Rows[i]["c_flagactcontador"].ToString();
                    factvence        = dt.Rows[i]["c_piemaxvenc"].ToString();

                    if (String.IsNullOrEmpty(factvence) == false)
                    {
                        hora    = Convert.ToInt32(dt.Rows[i]["n_horaRes"]);
                        minuto  = Convert.ToInt32(dt.Rows[i]["n_minuRes"]);
                        segundo = Convert.ToInt32(dt.Rows[i]["n_seguRes"]);
                    }
                    //  Bitmap b = new Bitmap(@"\\IBSERVER_1\Servidor de Archivos\Fotos\L17.jpg");
                    if (System.IO.File.Exists(@rutaimg))
                    {
                        Bitmap b = new Bitmap(rutaimg);
                        System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        b.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        byte[] byteImage = ms.ToArray();
                        imgBase64 = Convert.ToBase64String(byteImage);

                        dt.Rows[i][11] = "data:image/jpeg;base64," + imgBase64;
                        dt.AcceptChanges();
                    }

                    /*HtmlSeccion = " <td><tr >  <p style='font-weight: bold' >" + stittulo + "</p> </tr> </td>";
                     * HtmlSeccion = HtmlSeccion + "<td><tr >  " + sdetalle + "</tr></td>";
                     * HtmlSeccion = HtmlSeccion + "<td> <tr ><img  style='height: 100%; width: 100%; object-fit: contain' src='data:image/jpeg;base64," + imgBase64 + "' /></tr></td>";
                     * BodyHtml = BodyHtml + HtmlSeccion;*/
                }

                //  lblHeader.Text = "PROMOCIONES DEL DÍA " + DateTime.Now.ToShortDateString();
                repeatHtml.DataSource = dt;
                repeatHtml.DataBind();

                if (String.IsNullOrEmpty(factvence) == true || factvence == "")
                {
                    divConteo.Visible = false;
                }
                else
                {
                    lblfchavcto.InnerText = factvence + " ";
                }


                if (flagconteotiempo == "S")
                {
                    int tiempoTotal = (hora * 3600) + (minuto * 60) + segundo;
                    ClientScript.RegisterStartupScript(typeof(Page), "Script", "Activate(" + tiempoTotal + ")", true);
                }
            }
        }
Пример #29
0
 // accept changes (resets all RowState to unchanged)
 private void button1_Click(object sender, System.EventArgs e)
 {
     _dt.AcceptChanges();
 }
Пример #30
0
    private void Query(int Export)
    {
        DataTable  dtShow = new DataTable();
        DataColumn dc0    = new DataColumn("月份");
        //样品数_样品类型_项目类型
        DataColumn dc1_0 = new DataColumn("1_10_48,77_0", typeof(int));                                                    //地表水样品数
        DataColumn dc1_1 = new DataColumn("2_10_48,77_0", typeof(int));                                                    //地表水数据量
        DataColumn dc2_0 = new DataColumn("1_1_45,46,47,79,74_0", typeof(int));                                            //重点源废水样品数
        DataColumn dc2_1 = new DataColumn("2_1_45,46,47,79,74_0", typeof(int));                                            //重点源废水数据量
        DataColumn dc3_0 = new DataColumn("1_1_7,56,59_1", typeof(int));                                                   //大队委托水样品数
        DataColumn dc3_1 = new DataColumn("2_1_7,56,59_1", typeof(int));                                                   //大队委托水数据量
        DataColumn dc4_0 = new DataColumn("1_1,10,11_8,49_1", typeof(int));                                                //自送样水样品数
        DataColumn dc4_1 = new DataColumn("2_1,10,11_8,49_1", typeof(int));                                                //自送样水数据量
        DataColumn dc5_0 = new DataColumn("1_1_1,5,75_1", typeof(int));                                                    //三同时水样品数
        DataColumn dc5_1 = new DataColumn("2_1_1,5,75_1", typeof(int));                                                    //三同时水数据量
        DataColumn dc6_0 = new DataColumn("1_1,10,11_2,3,4,6,9,53,55,57,58,60,61,62,68,69,72,78,71_1", typeof(int));       //其他委托水样品数
        DataColumn dc6_1 = new DataColumn("2_1,10,11_2,3,4,6,9,53,55,57,58,60,61,62,68,69,72,78,71_1", typeof(int));       //其他委托水数据量

        DataColumn dc7_0  = new DataColumn("1_2,12_52,54_0", typeof(int));                                                 //气常规样品数
        DataColumn dc7_1  = new DataColumn("2_2,12_52,54_0", typeof(int));                                                 //气常规气数据量
        DataColumn dc8_0  = new DataColumn("1_2_63,70_0", typeof(int));                                                    //气重点源样品数
        DataColumn dc8_1  = new DataColumn("2_2_63,70_0", typeof(int));                                                    //气重点源气数据量
        DataColumn dc9_0  = new DataColumn("1_2_1,5,76_1", typeof(int));                                                   //气三同时样品数
        DataColumn dc9_1  = new DataColumn("2_2_1,5,76_1", typeof(int));                                                   //气三同时数据量
        DataColumn dc10_0 = new DataColumn("1_2,12_2,3,4,6,9,53,55,57,58,60,61,62,68,69,72,78,56,8,59,71_1", typeof(int)); //其他委托气样品数
        DataColumn dc10_1 = new DataColumn("2_2,12_2,3,4,6,9,53,55,57,58,60,61,62,68,69,72,78,56,8,59,71_1", typeof(int)); //其他委托气数据量

        DataColumn dc11_0 = new DataColumn("1_4,6,15,16_66,65,73,68,69_0", typeof(int));                                   //土壤、底质、煤样样品数
        DataColumn dc11_1 = new DataColumn("2_4,6,15,16_66,65,73,68,69_0", typeof(int));                                   //土壤、底质、煤样数据量
        DataColumn dc14_0 = new DataColumn("1_7_0_0", typeof(int));                                                        //噪声样品量
        DataColumn dc14_1 = new DataColumn("2_7_0_0", typeof(int));                                                        //噪声数据量
        DataColumn dc12_0 = new DataColumn("1_5_49,9_0", typeof(int));                                                     //桑叶氟化物样品数
        DataColumn dc12_1 = new DataColumn("2_5_49,9_0", typeof(int));                                                     //桑叶氟化物数据量
        DataColumn dc13_0 = new DataColumn("Samplesum", typeof(int));                                                      //样品数合计
        DataColumn dc13_1 = new DataColumn("sum", typeof(int));                                                            //数据量合计

        dtShow.Columns.Add(dc0);
        dtShow.Columns.Add(dc1_0);
        dtShow.Columns.Add(dc1_1);
        dtShow.Columns.Add(dc2_0);
        dtShow.Columns.Add(dc2_1);
        dtShow.Columns.Add(dc3_0);
        dtShow.Columns.Add(dc3_1);
        dtShow.Columns.Add(dc4_0);
        dtShow.Columns.Add(dc4_1);
        dtShow.Columns.Add(dc5_0);
        dtShow.Columns.Add(dc5_1);
        dtShow.Columns.Add(dc6_0);
        dtShow.Columns.Add(dc6_1);
        dtShow.Columns.Add(dc7_0);
        dtShow.Columns.Add(dc7_1);
        dtShow.Columns.Add(dc8_0);
        dtShow.Columns.Add(dc8_1);
        dtShow.Columns.Add(dc9_0);
        dtShow.Columns.Add(dc9_1);
        dtShow.Columns.Add(dc10_0);

        dtShow.Columns.Add(dc10_1);
        dtShow.Columns.Add(dc11_0);
        dtShow.Columns.Add(dc11_1);
        dtShow.Columns.Add(dc14_0);
        dtShow.Columns.Add(dc14_1);
        dtShow.Columns.Add(dc12_0);
        dtShow.Columns.Add(dc12_1);
        dtShow.Columns.Add(dc13_0);
        dtShow.Columns.Add(dc13_1);

        DateTime dtStartTime, dtEndTime;
        DateTime dt  = Convert.ToDateTime(txt_StartTime.Text);
        DateTime dt2 = Convert.ToDateTime(txt_EndTime.Text);

        dtStartTime = dt;  //Convert.ToDateTime(dt.Year + "-" + dt.Month + "-1");
        dtEndTime   = dt2; // Convert.ToDateTime(dt2.Year + "-" + dt2.Month + "-1");
        //dtEndTime = dtEndTime.AddMonths(1);
        if (dt.Year != dt2.Year)
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('不能跨年查询!');", true);
            return;
        }
        int    subMonth      = int.Parse(dt2.Month.ToString()) - int.Parse(dt.Month.ToString()) + 1;
        string strSql_Sample = "select *,month(AccessDate) m   from t_M_ReporInfo r inner join t_M_SampleInfor s on r.id=s.ReportID ";

        strSql_Sample += "where s.AccessDate >= '" + dtStartTime + "' and s.AccessDate < '" + dtEndTime + "'";
        DataSet dsSample = new MyDataOp(strSql_Sample).CreateDataSet();
        string  strSql   = "select *, month(AccessDate) m  from t_M_ReporInfo r inner join t_M_SampleInfor s on r.id=s.ReportID inner join t_MonitorItemDetail n on n.SampleID=s.id ";

        strSql += "where s.AccessDate >= '" + dtStartTime + "' and s.AccessDate < '" + dtEndTime + "' and n.delflag=0 ";
        DataSet ds = new MyDataOp(strSql).CreateDataSet();


        for (int mth = 0; mth < subMonth; mth++)
        {
            DataRow dradd = dtShow.NewRow();
            dradd[0] = int.Parse(dt.Month.ToString()) + mth;

            int j   = 1;
            int yps = 0;
            int sjl = 0;
            for (; j < dtShow.Columns.Count - 2; j = j + 2)
            {
                string col = dtShow.Columns[j].ColumnName;
                switch (col)
                {
                case "sum":
                case "Samplesum":
                    break;

                default: string[] list = col.Split('_');     //0:1-样品数,2-数据量;1-样品类型;2-项目类型;3-任务类型:0-例行监测,1-委托监测

                    string constr = "";
                    if (list[1] != "0")    //样品类型
                    {
                        constr += " and TypeID in(" + list[1] + ")";
                    }

                    if (list[2] != "0")    //项目类型
                    {
                        constr += " and ItemType in (" + list[2] + ")";
                    }

                    // if (list[1] == "5")
                    //{
                    //    constr += " and ItemType ='5'";// and SampleID in ( select SampleID  from t_MonitorItemDetail  where MonitorItem='25' )";
                    //}
                    if (list[3] != "0") //任务类型
                    {
                        constr += " and rwclass='" + list[3] + "'";
                    }
                    object ypobj = dsSample.Tables[0].Compute("sum(num)", " m='" + (dradd[0].ToString()) + "'" + constr);
                    //DataRow[] drsel = dsSample.Tables[0].Select(" m='" + (dradd[0].ToString()) + "'" + constr);
                    if (ypobj.ToString() != "")
                    {
                        dradd[j] = ypobj.ToString();
                        yps     += int.Parse(ypobj.ToString());
                    }
                    else
                    {
                        dradd[j] = "0";
                    }

                    DataRow[] drselnum = ds.Tables[0].Select(" m='" + (dradd[0].ToString()) + "' " + constr);
                    dradd[j + 1] = drselnum.Length;
                    sjl         += drselnum.Length;
                    break;
                }
            }
            dradd[j]     = yps;
            dradd[j + 1] = sjl;
            dtShow.Rows.Add(dradd);
            // strSql += " union all select " + (int.Parse(dt.Month.ToString()) + mth).ToString();
        }
        DataRow drhj = dtShow.NewRow();

        drhj[0] = "合计";
        for (int p = 1; p < dtShow.Columns.Count; p++)
        {
            object sum = dtShow.Compute("sum([" + dtShow.Columns[p].ColumnName + "])", "");
            drhj[p] = sum.ToString();
        }
        dtShow.Rows.Add(drhj);
        dtShow.AcceptChanges();
        if (dtShow.Rows.Count == 0)
        {
            //没有记录仍保留表头
            dtShow.Rows.Add(dtShow.NewRow());
            grdvw_List.DataSource = dtShow;
            grdvw_List.DataBind();
            int intColumnCount = grdvw_List.Rows[0].Cells.Count;
            grdvw_List.Rows[0].Cells.Clear();
            grdvw_List.Rows[0].Cells.Add(new TableCell());
            grdvw_List.Rows[0].Cells[0].ColumnSpan = intColumnCount;
        }
        else
        {
            grdvw_List.DataSource = dtShow;
            grdvw_List.DataBind();
        }
        ds.Dispose();
    }
Пример #31
0
    public DataTable GetGroupByDataTable(DataTable originDataTable, string aggregateOriginField1, string aggregateOriginField2, string[] groupByColumns, string aggregateNewField1, string aggregateNewField2, string primaryKey)
    {
        int       i;
        int       j;
        DataTable originDataTable_copy = originDataTable.Copy();

        if ((aggregateOriginField1 == "" ? true : aggregateOriginField1 == null))
        {
            bool     exsistColmn = false;
            DateTime now         = DateTime.Now;
            aggregateOriginField1 = string.Concat("T", now.ToString("yyyyMMddHHmmddfff"));
            foreach (DataColumn dc in originDataTable_copy.Columns)
            {
                if (dc.ColumnName == aggregateOriginField1)
                {
                    exsistColmn = true;
                }
            }
            if (!exsistColmn)
            {
                originDataTable_copy.Columns.Add(aggregateOriginField1, typeof(int));
            }
            for (i = 0; i < originDataTable_copy.Rows.Count; i++)
            {
                originDataTable_copy.Rows[i][aggregateOriginField1] = 0;
            }
            originDataTable_copy.AcceptChanges();
        }
        if ((aggregateNewField1 == "" ? true : aggregateNewField1 == null))
        {
            aggregateNewField1 = aggregateOriginField1;
        }
        if ((primaryKey == "" ? true : primaryKey == null))
        {
            primaryKey = "IDX";
            if (!originDataTable_copy.Columns.Contains(primaryKey))
            {
                originDataTable_copy.Columns.Add(primaryKey, typeof(int));
            }
            for (i = 0; i < originDataTable_copy.Rows.Count; i++)
            {
                originDataTable_copy.Rows[i][primaryKey] = i + 1;
            }
            originDataTable_copy.AcceptChanges();
        }
        string aggregateSumField1 = string.Format("{0}_{1}", "SUM", aggregateNewField1);
        string aggregateCntField1 = string.Format("{0}_{1}", "CNT", aggregateNewField1);
        string aggregateAvgField1 = string.Format("{0}_{1}", "AVG", aggregateNewField1);
        string aggregateSumField2 = string.Format("{0}_{1}", "SUM", aggregateNewField2);
        string aggregateCntField2 = string.Format("{0}_{1}", "CNT", aggregateNewField2);
        string aggregateAvgField2 = string.Format("{0}_{1}", "AVG", aggregateNewField2);

        if (!originDataTable_copy.Columns.Contains("IS_AGGEGATED"))
        {
            originDataTable_copy.Columns.Add("IS_AGGEGATED", typeof(int));
        }
        foreach (DataRow dr in originDataTable_copy.Rows)
        {
            dr["IS_AGGEGATED"] = 0;
        }
        DataTable     dataTempTable = originDataTable_copy.Clone();
        List <string> removeColList = new List <string>();

        foreach (DataColumn dataColumn in dataTempTable.Columns)
        {
            bool isContain = false;
            i = 0;
            while (i < (int)groupByColumns.Length)
            {
                if (!(groupByColumns[i] == dataColumn.ColumnName))
                {
                    if (i == (int)groupByColumns.Length - 1)
                    {
                        if (!isContain)
                        {
                            removeColList.Add(dataColumn.ColumnName);
                        }
                    }
                    i++;
                }
                else
                {
                    isContain = true;
                    break;
                }
            }
        }
        for (i = 0; i < removeColList.Count; i++)
        {
            dataTempTable.Columns.Remove(removeColList[i]);
        }
        dataTempTable.AcceptChanges();
        dataTempTable.Columns.Add(aggregateSumField1, typeof(double));
        dataTempTable.Columns.Add(aggregateCntField1, typeof(double));
        dataTempTable.Columns.Add(aggregateAvgField1, typeof(double));
        dataTempTable.Columns.Add(aggregateSumField2, typeof(double));
        dataTempTable.Columns.Add(aggregateCntField2, typeof(double));
        dataTempTable.Columns.Add(aggregateAvgField2, typeof(double));
        dataTempTable.Columns.Add(primaryKey, typeof(string));
        DataRow dataTempRow = null;

        DataRow[] dataRowCol = null;
        foreach (DataRow dataRow in originDataTable_copy.Rows)
        {
            dataRowCol = originDataTable_copy.Select(string.Concat(GetFilterString(dataRow, groupByColumns), " AND IS_AGGEGATED = 0"));
            double aggreSumData1 = 0;
            double aggreCntData1 = 0;
            double aggreAvgData1 = 0;
            double aggreSumData2 = 0;
            double aggreCntData2 = 0;
            double aggreAvgData2 = 0;
            string idx_array     = "";
            if ((int)dataRowCol.Length != 0)
            {
                for (i = 1; i <= (int)dataRowCol.Length; i++)
                {
                    aggreSumData1 += GetToDouble(dataRowCol[i - 1][aggregateOriginField1]);
                    if (!aggregateOriginField2.Equals(""))
                    {
                        aggreSumData2 += GetToDouble(dataRowCol[i - 1][aggregateOriginField2]);
                    }
                    if (aggreCntData1 == 0)
                    {
                        aggreCntData1 = (double)((int)dataRowCol.Length);
                    }
                    if (!aggregateOriginField2.Equals(""))
                    {
                        if (aggreCntData2 == 0)
                        {
                            aggreCntData2 = (double)((int)dataRowCol.Length);
                        }
                    }
                    aggreAvgData1 += GetToDouble(dataRowCol[i - 1][aggregateOriginField1]);
                    if (!aggregateOriginField2.Equals(""))
                    {
                        aggreAvgData2 += GetToDouble(dataRowCol[i - 1][aggregateOriginField2]);
                    }
                    if (i == (int)dataRowCol.Length)
                    {
                        aggreAvgData1 /= GetToDouble(i);
                    }
                    if (!aggregateOriginField2.Equals(""))
                    {
                        if (i == (int)dataRowCol.Length)
                        {
                            aggreAvgData2 /= GetToDouble(i);
                        }
                    }
                    idx_array = (i != 1 ? string.Concat(idx_array, ";", dataRowCol[i - 1][primaryKey]) : string.Concat(idx_array, dataRowCol[i - 1][primaryKey]));
                    dataRowCol[i - 1]["IS_AGGEGATED"] = 1;
                }
                dataTempRow = dataTempTable.NewRow();
                string[] strArrays = groupByColumns;
                for (j = 0; j < (int)strArrays.Length; j++)
                {
                    string groupByColumn = strArrays[j];
                    dataTempRow[groupByColumn] = dataRow[groupByColumn];
                }
                dataTempRow[aggregateSumField1] = aggreSumData1;
                dataTempRow[aggregateCntField1] = aggreCntData1;
                dataTempRow[aggregateAvgField1] = Math.Round(aggreAvgData1, 4);
                if (!aggregateOriginField2.Equals(""))
                {
                    dataTempRow[aggregateSumField2] = aggreSumData2;
                    dataTempRow[aggregateCntField2] = aggreCntData2;
                    dataTempRow[aggregateAvgField2] = Math.Round(aggreAvgData2, 4);
                }
                dataTempRow[primaryKey] = idx_array;
                dataTempTable.Rows.Add(dataTempRow);
            }
        }
        DataTable dataSotedTable = dataTempTable.Clone();

        dataRowCol = dataTempTable.Select("", GetSortString(groupByColumns));
        DataRow[] dataRowArray = dataRowCol;
        for (j = 0; j < (int)dataRowArray.Length; j++)
        {
            dataSotedTable.ImportRow(dataRowArray[j]);
        }
        originDataTable_copy.Dispose();
        dataTempTable.Dispose();
        return(dataSotedTable);
    }
Пример #32
0
                public DataTable Result(DataTable tblCur,DataTable tblPrev,GroupSignalsDest.SIGNAL[] arSignals)
                {
                    DataTable tableRes = new DataTable();

                    DataRow[] arSelIns = null;
                    DataRow   rowCur   = null
                    ,rowAdd
                    ,rowPrev           = null;
                    int idSgnl         = -1
                    ,tmDelta           = -1;
                    bool bConsoleDebug = false;

                    m_tblPrevRecieved = tblPrev.Copy();

                    if ((tblCur.Columns.Count > 2) &&
                        ((!(tblCur.Columns.IndexOf(@"ID") < 0)) && (!(tblCur.Columns.IndexOf(@"DATETIME") < 0))))
                    {
                        tblCur.Columns.Add(@"tmdelta",typeof(int));
                        tableRes = tblCur.Clone();

                        for (int s = 0; s < arSignals.Length; s++)
                        {
                            try
                            {
                                idSgnl = (arSignals[s] as HHandlerDbULoaderDest.GroupSignalsDest.SIGNALDest).m_idLink;

                                //arSelIns = (tblCur as DataTable).Select(string.Empty, @"ID, DATETIME");
                                arSelIns = (tblCur as DataTable).Select(@"ID=" + idSgnl,@"DATETIME");
                            }
                            catch (Exception e)
                            {
                                Logging.Logg().Exception(e,Logging.INDEX_MESSAGE.NOT_SET,@"statidsql::getTableIns () - ...");
                            }

                            if (!(arSelIns == null))
                            {
                                for (int i = 0; i < arSelIns.Length; i++)
                                {
                                    if (i < (arSelIns.Length - 1))
                                    {
                                        tableRes.ImportRow(arSelIns[i]);
                                        rowCur = tableRes.Rows[tableRes.Rows.Count - 1];
                                    }
                                    else
                                    {
                                        //Не вставлять без известной 'tmdelta'
                                        rowCur = null;
                                    }

                                    //Проверитьт № итерации
                                    if (i == 0)
                                    {//Только при прохождении 1-ой итерации цикла
                                        tmDelta = -1;
                                        //Определить 'tmdelta' для записи из предыдущего опроса
                                        rowAdd  = null;
                                        rowPrev = setTMDelta(idSgnl,(DateTime)arSelIns[i][@"DATETIME"],out tmDelta);

                                        if ((!(rowPrev == null)) &&
                                            (tmDelta > 0))
                                        {
                                            //Добавить из предыдущего опроса
                                            rowAdd = tableRes.Rows.Add();
                                            //Скопировать все значения
                                            foreach (DataColumn col in tableRes.Columns)
                                            {
                                                if (col.ColumnName.Equals(@"tmdelta") == true)
                                                {
                                                    //Для "нового" столбца - найденное значение
                                                    rowAdd[col.ColumnName] = tmDelta;
                                                }
                                                else
                                                {
                                                    //"Старые" значения
                                                    rowAdd[col.ColumnName] = rowPrev[col.ColumnName];
                                                }
                                            }

                                            if (bConsoleDebug == true)
                                            {
                                                Console.WriteLine(@"Установлен для ID=" + idSgnl + @", DATETIME=" + ((DateTime)rowAdd[@"DATETIME"]).ToString(@"dd.MM.yyyy HH:mm:ss.fff") + @" tmdelta=" + rowAdd[@"tmdelta"]);
                                            }
                                            else
                                            {
                                                ;
                                            }
                                        }
                                        else
                                        {
                                            ;
                                        }
                                    }
                                    else
                                    {
                                        //Определить смещение "соседних" значений сигнала
                                        long iTMDelta = (((DateTime)arSelIns[i][@"DATETIME"]).Ticks - ((DateTime)arSelIns[i - 1][@"DATETIME"]).Ticks) / TimeSpan.TicksPerMillisecond;
                                        rowPrev[@"tmdelta"] = (int)iTMDelta;
                                        if (bConsoleDebug == true)
                                        {
                                            Console.WriteLine(@", tmdelta=" + rowPrev[@"tmdelta"]);
                                        }
                                        else
                                        {
                                            ;
                                        }
                                    }

                                    if (bConsoleDebug == true)
                                    {
                                        if (!(rowCur == null))
                                        {
                                            Console.Write(@"ID=" + rowCur[@"ID"] + @", DATETIME=" + ((DateTime)rowCur[@"DATETIME"]).ToString(@"dd.MM.yyyy HH:mm:ss.fff"));
                                        }
                                        else
                                        {
                                            Console.Write(@"ID=" + arSelIns[i][@"ID"] + @", DATETIME=" + ((DateTime)arSelIns[i][@"DATETIME"]).ToString(@"dd.MM.yyyy HH:mm:ss.fff"));
                                        }
                                    }
                                    else
                                    {
                                        ;
                                    }

                                    rowPrev = rowCur;
                                }
                            }
                            else
                            {
                                ; //arSelIns == null
                            }
                            //Корректировать вывод
                            if (bConsoleDebug == true)
                            {
                                if (arSelIns.Length > 0)
                                {
                                    Console.WriteLine();
                                }
                                else
                                {
                                    ;
                                }
                            }
                            else
                            {
                                ;
                            }
                        } //Цикл по сигналам...
                    }
                    else
                    {
                        ; //Отсутствуют необходимые столбцы (т.е. у таблицы нет структуры)
                    }
                    tableRes.AcceptChanges();

                    return(tableRes);
                }
Пример #33
0
        protected override void InitUIControls()
        {
            #region Initial Equipment Location ComboBox

            this.cmbEquipmentLocation.Properties.Columns.Clear();
            this.cmbEquipmentLocation.Properties.Columns.Add(new LookUpColumnInfo(FMM_LOCATION_FIELDS.FIELD_LOCATION_NAME));
            this.cmbEquipmentLocation.Properties.ShowHeader    = false;
            this.cmbEquipmentLocation.Properties.DisplayMember = FMM_LOCATION_FIELDS.FIELD_LOCATION_NAME;
            this.cmbEquipmentLocation.Properties.ValueMember   = FMM_LOCATION_FIELDS.FIELD_LOCATION_KEY;

            #endregion

            #region Initial Equipment Group ComboBox

            this.cmbEquipmentGroup.Properties.Columns.Clear();
            this.cmbEquipmentGroup.Properties.Columns.Add(new LookUpColumnInfo(EMS_EQUIPMENT_GROUPS_FIELDS.FIELD_EQUIPMENT_GROUP_NAME));
            this.cmbEquipmentGroup.Properties.ShowHeader    = false;
            this.cmbEquipmentGroup.Properties.DisplayMember = EMS_EQUIPMENT_GROUPS_FIELDS.FIELD_EQUIPMENT_GROUP_NAME;
            this.cmbEquipmentGroup.Properties.ValueMember   = EMS_EQUIPMENT_GROUPS_FIELDS.FIELD_EQUIPMENT_GROUP_KEY;

            #endregion

            #region Initial Equipment ComboBox

            this.cmbEquipment.Properties.Columns.Clear();
            this.cmbEquipment.Properties.Columns.Add(new LookUpColumnInfo(EMS_EQUIPMENTS_FIELDS.FIELD_EQUIPMENT_NAME));
            this.cmbEquipment.Properties.ShowHeader    = false;
            this.cmbEquipment.Properties.DisplayMember = EMS_EQUIPMENTS_FIELDS.FIELD_EQUIPMENT_NAME;
            this.cmbEquipment.Properties.ValueMember   = EMS_EQUIPMENTS_FIELDS.FIELD_EQUIPMENT_KEY;

            #endregion

            #region Initial Check List Job State ComboBox

            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("CHECKLIST_JOB_STATE");

            dataTable.Rows.Add(string.Empty);
            dataTable.Rows.Add("ACTIVED");
            dataTable.Rows.Add("STARTED");
            dataTable.Rows.Add("COMPLETED");

            dataTable.AcceptChanges();

            this.cmbCheckListJobState.Properties.Columns.Clear();
            this.cmbCheckListJobState.Properties.Columns.Add(new LookUpColumnInfo("CHECKLIST_JOB_STATE"));
            this.cmbCheckListJobState.Properties.ShowHeader    = false;
            this.cmbCheckListJobState.Properties.DisplayMember = "CHECKLIST_JOB_STATE";
            this.cmbCheckListJobState.Properties.ValueMember   = "CHECKLIST_JOB_STATE";

            this.cmbCheckListJobState.Properties.DataSource = dataTable;

            #endregion

            #region Initial Check List Job Grid

            dataTable = GetEmptyCheckListJobDataTable();

            ControlUtils.InitialGridView(this.grvCheckListJobList, dataTable);

            #endregion

            #region Initial Check List Job Data Grid

            dataTable = GetEmptyCheckListJobDataDataTable();

            ControlUtils.InitialGridView(this.grvCheckListJobItemList, dataTable);

            GridColumn gridColumn = this.grvCheckListJobItemList.Columns.ColumnByFieldName(EMS_CHECKLIST_ITEM_FIELDS.FIELD_OPTIONAL);

            if (gridColumn != null)
            {
                RepositoryItemCheckEdit checkEdit = new RepositoryItemCheckEdit();

                checkEdit.QueryCheckStateByValue += new QueryCheckStateByValueEventHandler(ControlUtils.QueryCheckStateByValue);

                gridColumn.ColumnEdit = checkEdit;
            }

            #endregion
        }
Пример #34
0
    protected void GenerateReport(GridView grv, DataTable dtSalaryHead, int inBenefitHeadCount, Label lblGenFor, Label lblMonth)
    {
        string  strEmpID      = "";
        decimal dclSalHeadAmt = 0;

        this.InitializeSummaryTable(dtSalaryHead.Rows.Count + 11);
        int i = 5;
        int j = 1;

        foreach (DataRow dEmpRow in dtEmpPayroll.Rows)
        {
            dclEmpBenefits = 0;
            dclEmpDeduct   = 0;
            dclTotalSalary = 0;
            dclEmpPF       = 0;

            this.GetEmpBenefitsAmount(dtSalaryHead, dEmpRow["EMPID"].ToString().Trim(), dEmpRow["GROSSAMNT"].ToString());
            i = 5;
            if (strEmpID == dEmpRow["EMPID"].ToString().Trim())
            {
                continue;
            }
            DataRow nRow = dtPayrollSummary.NewRow();
            nRow[0] = Convert.ToString(j);
            nRow[1] = dEmpRow["EMPID"].ToString().Trim();
            nRow[2] = dEmpRow["FULLNAME"].ToString().Trim();
            nRow[3] = dEmpRow["JobTitleName"].ToString().Trim();
            nRow[4] = dEmpRow["GradeName"].ToString().Trim();

            foreach (DataRow dSalRow in dtSalaryHead.Rows)
            {
                if (i - 5 == dtGrossSalHead.Rows.Count)
                {
                    nRow[i] = Common.RoundDecimal(dEmpRow["GROSSAMNT"].ToString(), 0);
                    i++;
                }
                //if ((i - 5) - dtGrossSalHead.Rows.Count == inBenefitHeadCount + 1)
                //{
                //    nRow[i] = dclEmpBenefits.ToString();
                //    i++;
                //}
                if ((i - 5) - dtGrossSalHead.Rows.Count == inBenefitHeadCount + 1)
                {
                    nRow[i] = dclTotalSalary.ToString();
                    i++;

                    dclSalHeadAmt = 0;
                    dclSalHeadAmt = this.GetSalHeadAmt(dEmpRow["EMPID"].ToString().Trim(), dSalRow["SHEADID"].ToString().Trim());
                    if (dSalRow["DISPLAYTYPE"].ToString().Trim() == "D")
                    {
                        if (dclSalHeadAmt > 0)
                        {
                            dclSalHeadAmt = dclSalHeadAmt * -1;
                        }
                    }

                    nRow[i] = dclSalHeadAmt.ToString();
                    i++;
                }
                else
                {
                    dclSalHeadAmt = 0;
                    dclSalHeadAmt = this.GetSalHeadAmt(dEmpRow["EMPID"].ToString().Trim(), dSalRow["SHEADID"].ToString().Trim());
                    if (dSalRow["DISPLAYTYPE"].ToString().Trim() == "D")
                    {
                        if (dclSalHeadAmt > 0)
                        {
                            dclSalHeadAmt = dclSalHeadAmt * -1;
                        }
                    }

                    nRow[i] = dclSalHeadAmt.ToString();
                    i++;
                }
            }

            nRow[i] = dclEmpDeduct.ToString();
            i++;

            nRow[i] = Common.RoundDecimal(dEmpRow["NETPAY"].ToString(), 0);
            i++;

            nRow[i] = "0";
            i++;

            nRow[i] = dclEmpPF.ToString();

            dtPayrollSummary.Rows.Add(nRow);
            dtPayrollSummary.AcceptChanges();
            strEmpID = dEmpRow["EMPID"].ToString().Trim();
            j++;
        }

        grv.DataSource = dtPayrollSummary;
        grv.DataBind();

        if (dtPayrollSummary.Rows.Count > 0)
        {
            this.FormatGridView(grv, dtSalaryHead, inBenefitHeadCount);
            this.GetSummaryTotal(grv);
            if (ddlGeneratefor.SelectedValue.Trim() == "E")
            {
                lblGenFor.Text = grv.Rows[0].Cells[2].Text.Trim() + " [" + grv.Rows[0].Cells[1].Text.Trim() + "] ";
            }

            if (dtEmpPayroll.Rows[0]["SALARYTYPE"].ToString().Trim() == "S")
            {
                lblMonth.Text = "Salary for the month of " + ddlMonth.SelectedItem.Text + " " + ddlYear.SelectedItem.Text;
            }
            else if (dtEmpPayroll.Rows[0]["SALARYTYPE"].ToString().Trim() == "B")
            {
                lblMonth.Text = "Bonus for the month of " + ddlMonth.SelectedItem.Text + " " + ddlYear.SelectedItem.Text;
            }
        }
        else
        {
            lblGenFor.Text = "";
            lblMonth.Text  = "";
        }
    }
Пример #35
0
        /// <summary>
        /// 审批选中的多条生产计划单
        /// </summary>
        public bool ApproveProductionSchedule_Multi(DataTable headTable, int saveTypeInt)
        {
            string   psNoListStr = "";
            DateTime serverTime  = BaseSQL.GetServerDateTime();

            for (int i = 0; i < headTable.Rows.Count; i++)
            {
                if (DataTypeConvert.GetBoolean(headTable.Rows[i]["Select"]))
                {
                    psNoListStr += string.Format("'{0}',", DataTypeConvert.GetString(headTable.Rows[i]["PsNo"]));
                    headTable.Rows[i]["PsState"] = 2;
                }
            }

            psNoListStr = psNoListStr.Substring(0, psNoListStr.Length - 1);
            if (!CheckPSState(headTable, psNoListStr, false, true, true, false))
            {
                return(false);
            }

            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);
                        cmd.CommandText = string.Format("Update PB_ProductionSchedule set PsState={1} where PsNo in ({0})", psNoListStr, 2);
                        cmd.ExecuteNonQuery();

                        //保存日志到日志表中
                        DataRow[] headRows = headTable.Select("select=1");
                        for (int i = 0; i < headRows.Length; i++)
                        {
                            string logStr = LogHandler.RecordLog_OperateRow(cmd, "生产计划单", headRows[i], "PsNo", "审批", SystemInfo.user.EmpName, serverTime.ToString("yyyy-MM-dd HH:mm:ss"));

                            string psNoStr         = DataTypeConvert.GetString(headRows[i]["PsNo"]);
                            string codeFileNameStr = DataTypeConvert.GetString(headRows[i]["CodeFileName"]);
                            int    qtyInt          = DataTypeConvert.GetInt(headRows[i]["PlannedQty"]);
                            //根据BOM的定义生成物料明细
                            if (saveTypeInt == 1)//保存BOM的第一级节点
                            {
                                cmd.CommandText = string.Format("insert into PB_ProductionScheduleBom (PsNo, CodeFileName, Qty, TotalQty) select '{1}', LevelMaterielNo, Qty, Qty * {2} from BS_BomMateriel where MaterielNo = '{0}'", codeFileNameStr, psNoStr, qtyInt);
                                cmd.ExecuteNonQuery();
                            }
                            else//保存BOM的最末节点
                            {
                                SqlCommand cmd_proc  = new SqlCommand("", conn, trans);
                                string     errorText = "";
                                if (!Update_ProductionScheduleBom(cmd_proc, psNoStr, out errorText))
                                {
                                    trans.Rollback();
                                    MessageHandler.ShowMessageBox("更新生产计划单BOM信息错误--" + errorText);
                                    return(false);
                                }
                            }
                        }

                        trans.Commit();
                        headTable.AcceptChanges();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        headTable.RejectChanges();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Пример #36
0
        private void btnGhi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (cMND_PASSPORTTextEdit.Enabled == true)
            {
                if (cMND_PASSPORTTextEdit.Text.Trim() == "" || cMND_PASSPORTTextEdit.Text.Length < 9)
                {
                    MessageBox.Show("Chứng minh nhân dân của khách hàng không được thiếu!", "", MessageBoxButtons.OK);
                    cMND_PASSPORTTextEdit.Focus();
                    return;
                }
                else
                {
                    cMND_PASSPORTTextEdit.Text = cMND_PASSPORTTextEdit.Text.ToUpper();
                }
                hoKHTextEdit.Text = DataUtil.xoaKhoangTrang(hoKHTextEdit.Text);
                if (hoKHTextEdit.Text.Trim() == "")
                {
                    MessageBox.Show("Họ khách hàng không được trống!", "", MessageBoxButtons.OK);
                    hoKHTextEdit.Focus();
                    return;
                }
                tenKHTextEdit.Text = DataUtil.xoaKhoangTrang(tenKHTextEdit.Text);
                if (tenKHTextEdit.Text.Trim() == "")
                {
                    MessageBox.Show("Tên khách hàng không được trống!", "", MessageBoxButtons.OK);
                    tenKHTextEdit.Focus();
                    return;
                }
                if (soDienThoaiKHTextEdit.Text.Trim() != "" && soDienThoaiKHTextEdit.Text.Trim().Length < 10)
                {
                    MessageBox.Show("Độ dài SDT phải lớn hơn 9");
                    soDienThoaiKHTextEdit.Focus();
                    return;
                }
                nganHangTextEdit.Text = DataUtil.xoaKhoangTrang(nganHangTextEdit.Text);

                //if (!IsValidEmail(emailTextEdit.Text) && emailTextEdit.Text.Trim() != "")
                //{
                //    MessageBox.Show("Email không đúng định dạng");
                //    emailTextEdit.Focus();
                //    return;

                //}
                try
                {
                    dtUNDOKHACHHANG.RejectChanges();
                    DataRowView drv = (DataRowView)kHACHHANGBindingSource.Current;
                    dtUNDOKHACHHANG.NewRow();
                    dtUNDOKHACHHANG.Rows.Add(cMND_PASSPORTTextEdit.Text, hoKHTextEdit.Text.Trim(), tenKHTextEdit.Text.Trim(), soDienThoaiKHTextEdit.Text, gioiTinhKHCheckEdit.Checked, ngaySinhKHDateEdit.DateTime, "", sTKSpinEdit.Text, nganHangTextEdit.Text, chiNhanhNHTextEdit.Text, Action);
                    dtUNDOKHACHHANG.AcceptChanges();
                    kHACHHANGBindingSource.EndEdit();
                    kHACHHANGBindingSource.ResetCurrentItem();
                    this.kHACHHANGTableAdapter.Connection.ConnectionString = DataUtil.connstr;
                    this.kHACHHANGTableAdapter.Update(this.kHACHSANDataSet.KHACHHANG);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Lỗi ghi khách hàng.\n" + ex.Message, "", MessageBoxButtons.OK);
                    return;
                }
            }
            //update
            else
            {
                if (cMND_PASSPORTTextEdit.Text.Trim() == "" || cMND_PASSPORTTextEdit.Text.Length < 9)
                {
                    MessageBox.Show("Chứng minh nhân dân của khách hàng không được thiếu!", "", MessageBoxButtons.OK);
                    cMND_PASSPORTTextEdit.Focus();
                    return;
                }
                hoKHTextEdit.Text = DataUtil.xoaKhoangTrang(hoKHTextEdit.Text);
                if (hoKHTextEdit.Text.Trim() == "")
                {
                    MessageBox.Show("Họ khách hàng không được trống!", "", MessageBoxButtons.OK);
                    hoKHTextEdit.Focus();
                    return;
                }
                tenKHTextEdit.Text = DataUtil.xoaKhoangTrang(tenKHTextEdit.Text);
                if (tenKHTextEdit.Text.Trim() == "")
                {
                    MessageBox.Show("Tên khách hàng không được trống!", "", MessageBoxButtons.OK);
                    tenKHTextEdit.Focus();
                    return;
                }
                if (soDienThoaiKHTextEdit.Text.Trim() != "" && soDienThoaiKHTextEdit.Text.Trim().Length < 10)
                {
                    MessageBox.Show("Độ dài số điện thoại phải lớn hơn 9");
                    soDienThoaiKHTextEdit.Focus();
                    return;
                }
                nganHangTextEdit.Text   = DataUtil.xoaKhoangTrang(nganHangTextEdit.Text);
                chiNhanhNHTextEdit.Text = DataUtil.xoaKhoangTrang(chiNhanhNHTextEdit.Text);

                //if (!IsValidEmail(emailTextEdit.Text) && emailTextEdit.Text.Trim() != "")
                //{
                //    MessageBox.Show("Email không đúng định dạng");
                //    emailTextEdit.Focus();
                //    return;
                //}
                try
                {
                    DateTime    sv  = ngaySinhKHDateEdit.DateTime;
                    DataRowView drv = (DataRowView)kHACHHANGBindingSource.Current;
                    drv[5] = sv;
                    kHACHHANGBindingSource.EndEdit();
                    kHACHHANGBindingSource.ResetCurrentItem();
                    this.kHACHHANGTableAdapter.Connection.ConnectionString = DataUtil.connstr;
                    this.kHACHHANGTableAdapter.Update(this.kHACHSANDataSet.KHACHHANG);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Lỗi ghi khách hàng.\n" + ex.Message, "", MessageBoxButtons.OK);
                    dtUNDOKHACHHANG.Rows.RemoveAt(dtUNDOKHACHHANG.Rows.Count - 1);
                    return;
                }
            }
            kHACHHANGGridControl.Enabled = true;
            btnThem.Enabled   = btnHieuChinh.Enabled = btnXoa.Enabled = btnReload.Enabled = true;
            btnGhi.Enabled    = btnHuy.Enabled = false;
            btnUndo.Enabled   = true;
            groupBox1.Enabled = false;
        }
Пример #37
0
        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            if (change)
            {
                if (DialogResult.Yes ==
                    MessageBox.Show("Сохранить изменения", "Запрос на сохранение?", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    change = false;
                    save();
                    update_table();
                }
                else
                {
                    MessageBox.Show("Изменения не сохранены!");
                    change = false;
                }
            }

            foreach (DataGridViewRow r in dataGridView1.SelectedRows)
            {
                id_list.Clear();
                name_list.Clear();
                dataWorker = sql;
                if (Convert.ToInt32(r.Cells[2].Value) == 6)
                {
                    dataWorker = sqlVVO;
                }
                indexrow  = Convert.ToInt32(r.Cells[0].Value);
                indexName = Convert.ToString(r.Cells["Column2"].Value);
                // Console.WriteLine(r.Cells[2].Value);
                DataTable groupsRN = MakeGroupsTable_chk();
                ArrayList groups   = dataWorker.GetGroups(Convert.ToInt32(r.Cells[2].Value));
                foreach (Group group in groups)
                {
                    if (indexrow != group.Id)
                    {
                        groupRow          = groupsRN.NewRow();
                        groupRow["id"]    = group.Id;
                        groupRow["cname"] = group.Name;
                        groupRow["dep"]   = Convert.ToInt32(r.Cells[2].Value);
                        groupRow["chk"]   = false;
                        groupsRN.Rows.Add(groupRow);
                    }
                    else
                    {
                        id_list.Add(group.Id);
                        name_list.Add(group.Name);
                        indexName = group.Name;
                    }
                }
                string tmpstr    = "";
                string nameotdel = "";
                string idotdel   = "";
                id_to_del = 0;
                DataTable dtGroupDataTable = sql.getGroupGroup(Convert.ToInt32(r.Cells[2].Value));
                foreach (DataRow row in dtGroupDataTable.Rows)
                {
                    tmpstr = Convert.ToString(row["val"]);

                    string[] split = tmpstr.Split(new Char[] { ',', '\t', '\n' });
                    for (int j = 0; j < split.Length; j++)
                    {
                        //         Console.WriteLine(split[j]);
                        foreach (DataRow f in groupsRN.Rows)
                        {
                            if (split[j] == f["id"].ToString())
                            {
                                f["chk"] = true;
                                if (indexrow != Convert.ToInt32(split[0]))
                                {
                                    f.Delete();
                                }
                                if (indexrow == Convert.ToInt32(split[0]) && id_to_del == 0)
                                {
                                    id_to_del = Convert.ToInt32(row["id"]);
                                }
                                break;
                            }
                        }
                        groupsRN.AcceptChanges();
                    }
                    //MessageBox.Show(nameotdel);
                    groupsRN.AcceptChanges();
                }
                foreach (DataRow row in groupsRN.Rows)
                {
                    if (Convert.ToBoolean(row["chk"]))
                    {
                        name_list.Add(row["cname"]);
                        id_list.Add(row["id"]);
                    }
                }
                dataGridView2.DataSource = groupsRN;
                //MessageBox.Show(id_to_del.ToString());
            }
        }
Пример #38
0
        private void btnUndo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dtUNDOKHACHHANG.Rows.Count - 1 >= 0)
            {
                DataRow dr   = dtUNDOKHACHHANG.Rows[dtUNDOKHACHHANG.Rows.Count - 1];
                String  temp = dr[10].ToString();
                if (temp.Equals("DELETE"))
                {
                    try
                    {
                        string sql = "DELETE FROM KHACHHANG WHERE CMND_PASSPORT ='" + dr[0].ToString() + "'";
                        if (DataUtil.ExecQueryString(sql))
                        {
                            kHACHSANDataSet.KHACHHANG.RejectChanges();
                            DataRow dt = kHACHSANDataSet.KHACHHANG.Rows.Find(dr[0].ToString());
                            kHACHSANDataSet.KHACHHANG.Rows.Remove(dt);
                            kHACHSANDataSet.KHACHHANG.AcceptChanges();
                            dtREDOKHACHHANG.RejectChanges();
                            dtREDOKHACHHANG.NewRow();
                            dtREDOKHACHHANG.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3], dr[4], dr[5], dr[6], dr[7], dr[8], dr[9], "INSERT");
                            dtREDOKHACHHANG.AcceptChanges();
                            dtUNDOKHACHHANG.RejectChanges();
                            dtUNDOKHACHHANG.Rows.RemoveAt(dtUNDOKHACHHANG.Rows.Count - 1);
                            dtUNDOKHACHHANG.AcceptChanges();
                            updatetable();
                        }
                    }
                    catch (Exception e1)
                    {
                        MessageBox.Show("WHAT's Error: " + e1.Message, "", MessageBoxButtons.OK);
                    }
                }
                else if (temp.Equals("UPDATE"))
                {
                    try
                    {
                        string sql = "UPDATE [dbo].[KHACHHANG] SET [CMND_PASSPORT] = '" + dr[0] + "',[HoKH] = N'" + dr[1] + "',[TenKH] = N'" + dr[2] + "',[SoDienThoaiKH] = '" + dr[3] + "',[GioiTinhKH] ='" + dr[4] + "' ,[NgaySinhKH] = '" + dr[5] + "',[Email] = '" + dr[6] + "',[STK] =" + dr[7] + ",[NganHang] = N'" + dr[8] + "',[ChiNhanhNH] = N'" + dr[9] + "'WHERE CMND_PASSPORT='" + dr[0] + "'";
                        if (DataUtil.ExecQueryString(sql))
                        {
                            kHACHSANDataSet.KHACHHANG.RejectChanges();
                            DataRow dt = kHACHSANDataSet.KHACHHANG.Rows.Find(dr[0].ToString());
                            dtREDOKHACHHANG.RejectChanges();
                            dtREDOKHACHHANG.NewRow();
                            dtREDOKHACHHANG.Rows.Add(dr[0].ToString(), dt[1].ToString(), dt[2].ToString(), dt[3], dt[4], dt[5], dt[6], dt[7], dt[8], dt[9], "UPDATE");
                            dt[1] = dr[1];
                            dt[2] = dr[2];
                            dt[3] = dr[3];
                            dt[4] = dr[4];
                            dt[5] = dr[5];
                            dt[6] = dr[6];
                            dt[7] = dr[7];
                            dt[8] = dr[8];
                            dt[9] = dr[9];
                            kHACHSANDataSet.KHACHHANG.AcceptChanges(); dtREDOKHACHHANG.AcceptChanges();
                            dtUNDOKHACHHANG.RejectChanges();
                            dtUNDOKHACHHANG.Rows.RemoveAt(dtUNDOKHACHHANG.Rows.Count - 1);
                            dtUNDOKHACHHANG.AcceptChanges();
                            updatetable();
                        }
                    }
                    catch (Exception e1)
                    {
                        MessageBox.Show("WHAT's Error: " + e1.Message, "", MessageBoxButtons.OK);
                    }
                }
                else if (temp.Equals("INSERT"))
                {
                    try
                    {
                        string sql = "INSERT INTO [KHACHHANG]([CMND_PASSPORT],[HoKH],[TenKH],[SoDienThoaiKH],[GioiTinhKH],[NgaySinhKH],[Email],[STK],[NganHang],[ChiNhanhNH]) VALUES('" + dr[0] + "',N'" + dr[1] + "',N'" + dr[2] + "','" + dr[3] + "','" + dr[4] + "','" + dr[5] + "','" + dr[6] + "'," + dr[7] + ",'" + dr[8] + "','" + dr[9] + "')";
                        if (DataUtil.ExecQueryString(sql))
                        {
                            kHACHSANDataSet.KHACHHANG.RejectChanges();
                            kHACHSANDataSet.KHACHHANG.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2], dr[3], dr[4], dr[5], dr[6], dr[7], dr[8], dr[9]);
                            kHACHSANDataSet.KHACHHANG.AcceptChanges();
                            dtREDOKHACHHANG.RejectChanges();
                            dtREDOKHACHHANG.NewRow();
                            dtREDOKHACHHANG.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3], dr[4], dr[5], dr[6], dr[7], dr[8], dr[9], "DELETE");
                            dtREDOKHACHHANG.AcceptChanges();
                            dtUNDOKHACHHANG.RejectChanges();
                            dtUNDOKHACHHANG.Rows.RemoveAt(dtUNDOKHACHHANG.Rows.Count - 1);
                            dtUNDOKHACHHANG.AcceptChanges();
                            updatetable();
                        }
                    }
                    catch (Exception e1)
                    {
                        MessageBox.Show("WHAT's Error: " + e1.Message, "", MessageBoxButtons.OK);
                    }
                }
                if (btnThem.Enabled == false)
                {
                    kHACHHANGBindingSource.Position = vitri;
                }
                btnRedo.Enabled = true;
                if (dtUNDOKHACHHANG.Rows.Count - 1 < 0)
                {
                    btnUndo.Enabled = false;
                }
            }

            kHACHHANGGridControl.Enabled = true;
            groupBox1.Enabled            = false;
            btnThem.Enabled = btnHieuChinh.Enabled = btnXoa.Enabled = btnReload.Enabled = true;
            btnGhi.Enabled  = btnHuy.Enabled = false;
        }
Пример #39
0
        public void bug672113_MulpleColConstraint()
        {
            DataTable FirstTable = new DataTable("First Table");
            DataColumn col0 = new DataColumn("empno", typeof(int));
            DataColumn col1 = new DataColumn("name", typeof(string));
            DataColumn col2 = new DataColumn("age", typeof(int));
            FirstTable.Columns.Add(col0);
            FirstTable.Columns.Add(col1);
            FirstTable.Columns.Add(col2);
            DataColumn[] primkeys = new DataColumn[2];
            primkeys[0] = FirstTable.Columns[0];
            primkeys[1] = FirstTable.Columns[1];
            FirstTable.Constraints.Add("PRIM1", primkeys, true);

            DataTable SecondTable = new DataTable("Second Table");
            col0 = new DataColumn("field1", typeof(int));
            col1 = new DataColumn("field2", typeof(int));
            col2 = new DataColumn("field3", typeof(int));
            SecondTable.Columns.Add(col0);
            SecondTable.Columns.Add(col1);
            SecondTable.Columns.Add(col2);

            primkeys[0] = SecondTable.Columns[0];
            primkeys[1] = SecondTable.Columns[1];
            SecondTable.Constraints.Add("PRIM2", primkeys, true);

            DataRow row1 = FirstTable.NewRow();
            row1["empno"] = 1;
            row1["name"] = "Test";
            row1["age"] = 32;
            FirstTable.Rows.Add(row1);
            FirstTable.AcceptChanges();
            Assert.Equal(32, FirstTable.Rows[0]["age"]);

            row1 = SecondTable.NewRow();
            row1["field1"] = 10000;
            row1["field2"] = 12000;
            row1["field3"] = 1000;
            SecondTable.Rows.Add(row1);
            SecondTable.AcceptChanges();
            Assert.Equal(12000, SecondTable.Rows[0]["field2"]);
        }
Пример #40
0
        /// <summary>
        ///     Returns the layout of the board
        /// </summary>
        /// <param name="boardID"> The board ID. </param>
        /// <param name="userID"> The user ID. </param>
        /// <param name="categoryID"> The category ID. </param>
        /// <param name="parentID"> The parent ID. </param>
        /// <returns> The board layout. </returns>
        public DataSet BoardLayout(int boardID, int userID, int?categoryID, int?parentID)
        {
            if (categoryID.HasValue && categoryID == 0)
            {
                categoryID = null;
            }

            using (var ds = new DataSet())
            {
                // get the cached version of forum moderators if it's valid
                DataTable moderator;
                if (this.BoardSettings.ShowModeratorList)
                {
                    moderator = this.GetModerators();
                }
                else
                {
                    // add dummy table.
                    moderator = new DataTable("Moderator");
                    moderator.Columns.AddRange(
                        new[]
                    {
                        new DataColumn("ForumID", typeof(int)), new DataColumn("ForumName", typeof(string)),
                        new DataColumn("ModeratorName", typeof(string)),
                        new DataColumn("ModeratorDisplayName", typeof(string)),
                        new DataColumn("ModeratorEmail", typeof(string)),
                        new DataColumn("ModeratorAvatar", typeof(string)),
                        new DataColumn("ModeratorAvatarImage", typeof(bool)),
                        new DataColumn("Style", typeof(string)), new DataColumn("IsGroup", typeof(bool))
                    });
                }

                // insert it into this DataSet
                ds.Tables.Add(moderator.Copy());

                // get the Category Table
                DataTable category = this.DataCache.GetOrSet(
                    Constants.Cache.ForumCategory,
                    () =>
                {
                    var catDt       = this.DbFunction.GetAsDataTable(cdb => cdb.category_list(boardID, null));
                    catDt.TableName = "Category";
                    return(catDt);
                },
                    TimeSpan.FromMinutes(this.BoardSettings.BoardCategoriesCacheTimeout));

                // add it to this dataset
                ds.Tables.Add(category.Copy());

                DataTable categoryTable = ds.Tables["Category"];

                if (categoryID.HasValue)
                {
                    // make sure this only has the category desired in the dataset
                    foreach (
                        DataRow row in
                        categoryTable.AsEnumerable().Where(row => row.Field <int>("CategoryID") != categoryID))
                    {
                        // delete it...
                        row.Delete();
                    }

                    categoryTable.AcceptChanges();
                }

                DataTable forum = LegacyDb.forum_listread(
                    boardID,
                    userID,
                    categoryID,
                    parentID,
                    this.BoardSettings.UseStyledNicks,
                    this.BoardSettings.UseReadTrackingByDatabase);

                forum.TableName = "Forum";
                ds.Tables.Add(forum.Copy());

                ds.Relations.Add(
                    "FK_Forum_Category",
                    categoryTable.Columns["CategoryID"],
                    ds.Tables["Forum"].Columns["CategoryID"],
                    false);

                ds.Relations.Add(
                    "FK_Moderator_Forum",
                    ds.Tables["Forum"].Columns["ForumID"],
                    ds.Tables["Moderator"].Columns["ForumID"],
                    false);

                bool deletedCategory = false;

                // remove empty categories...
                foreach (
                    DataRow row in
                    categoryTable.SelectTypedList(
                        row => new { row, childRows = row.GetChildRows("FK_Forum_Category") })
                    .Where(@t => [email protected]())
                    .Select(@t => @t.row))
                {
                    // remove this category...
                    row.Delete();
                    deletedCategory = true;
                }

                if (deletedCategory)
                {
                    categoryTable.AcceptChanges();
                }

                return(ds);
            }
        }
Пример #41
0
        public void RejectChanges()
        {
            DataTable dt = new DataTable();
            DataColumn dc0 = new DataColumn("Col0", typeof(int));
            DataColumn dc1 = new DataColumn("Col1", typeof(int));
            dt.Columns.Add(dc0);
            dt.Columns.Add(dc1);
            dt.Rows.Add(new object[] { 1234 });
            dt.AcceptChanges();
            DataRow dr = dt.Rows[0];

            dr[0] = 567;
            dr[1] = 789;
            dr.RejectChanges();

            // RejectChanges - row 0
            Assert.Equal(1234, (int)dr[0]);

            // RejectChanges - row 1
            Assert.Equal(DBNull.Value, dr[1]);

            dr.Delete();
            dr.RejectChanges();

            // RejectChanges - count
            Assert.Equal(1, dt.Rows.Count);
        }
Пример #42
0
    public void DataLoad()
    {
        this.lnkFirst.CommandName = "FirstPage";
        this.lnkPrev.CommandName  = "PrevPage";
        this.lnkNext.CommandName  = "NextPage";
        this.lnkLast.CommandName  = "FirstPage";
        this.SetControls();
        if (this._TotalRecord > 0)
        {
            DataRow row;
            this._TotalPages = this._TotalRecord / this._PageSize;
            if ((this._TotalPages * this._PageSize) != this._TotalRecord)
            {
                this._TotalPages++;
            }
            this.lnkFirst.CommandArgument = "1";
            if (_CurrentPage > 1)
            {
                this.lnkPrev.CommandArgument = System.Convert.ToString((int)(this._CurrentPage - 1));
            }
            else
            {
                this.lnkPrev.CommandArgument = System.Convert.ToString((int)(this._CurrentPage));
            }

            this.lnkNext.CommandArgument = System.Convert.ToString((int)(this._CurrentPage + 1));
            this.lnkLast.CommandArgument = this._TotalPages.ToString();
            DataTable table = new DataTable();
            new DataView();
            table.Columns.Add(new DataColumn("PageNumber"));
            table.Columns.Add(new DataColumn("ISDisplayCurrent", typeof(bool)));
            table.Columns.Add(new DataColumn("ISDisplayLink", typeof(bool)));
            if (this._CurrentPage > this._TotalPages)
            {
                this._CurrentPage = 1;
            }
            int num  = 1;
            int num2 = 1;
            int num3 = 0;
            int num4 = 0;
            if (this._CurrentPage == 1)
            {
                num = 1;
            }
            if (this._CurrentPage > 1)
            {
                num3 = this._TotalNumberPaging / 2;
                num  = this._CurrentPage - num3;
                if (num < 1)
                {
                    num = 1;
                }
            }
            num3 = num;
            while (num <= this._TotalPages)
            {
                if (num2 > this._TotalNumberPaging)
                {
                    break;
                }
                if (num4 == 0)
                {
                    num4 = num;
                }
                row = table.NewRow();
                row["PageNumber"] = num.ToString();
                table.Rows.Add(row);
                num2++;
                num++;
            }
            if (num2 <= this._TotalNumberPaging)
            {
                int num5 = this._CurrentPage - 1;
                while ((num2 <= this._TotalNumberPaging) && (num5 > 0))
                {
                    num3--;
                    if (num3 > 0)
                    {
                        row = table.NewRow();
                        row["PageNumber"] = num3.ToString();
                        table.Rows.Add(row);
                        num4 = num3;
                    }
                    num5--;
                    num2++;
                }
            }
            table.AcceptChanges();
            this.rptPaging.DataSource = table.DefaultView;
            this.rptPaging.DataBind();
            if (this._CurrentPage == 1)
            {
                this.ShowFirstLink(false);
                this.ShowPrevLink(false);
                this.pnl_First.CssClass = "nav";
                this.pnl_Prev.CssClass  = "nav";
            }
            else
            {
                this.ShowFirstLink(true);
                this.ShowPrevLink(true);
                this.pnl_First.CssClass = "";
                this.pnl_Prev.CssClass  = "";
            }
            if (this._CurrentPage == this._TotalPages)
            {
                this.ShowLastLink(false);
                this.ShowNextLink(false);
                this.pnl_Next.CssClass = "nav";
                this.pnl_Last.CssClass = "nav";
            }
            else
            {
                this.ShowLastLink(true);
                this.ShowNextLink(true);
                this.pnl_Next.CssClass = "";
                this.pnl_Last.CssClass = "";
            }
            RepeaterItemCollection items = this.rptPaging.Items;
            num3 = 0;
            while (num3 < items.Count)
            {
                LinkButton button = (LinkButton)items[num3].FindControl("lnkPaging");
                Label      label  = (Label)items[num3].FindControl("lblPaging");
                if (num4 == this._CurrentPage)
                {
                    label.Visible  = true;
                    button.Visible = false;
                }
                else
                {
                    label.Visible  = false;
                    button.Visible = true;
                }
                label.Text             = System.Convert.ToString(num4);
                button.CommandArgument = System.Convert.ToString(num4);
                button.Text            = System.Convert.ToString(num4);
                button.CommandName     = "SelectPaging";
                num3++;
                num4++;
            }
        }
    }
Пример #43
0
        public void setAdded_testRollback()
        {
            DataTable table = new DataTable();
            table.Columns.Add("col1", typeof(int));
            table.Columns.Add("col2", typeof(int));

            table.Rows.Add(new object[] { 1, 1 });
            table.AcceptChanges();

            table.Rows[0].SetAdded();
            table.RejectChanges();
            Assert.Equal(0, table.Rows.Count);
        }
Пример #44
0
        private void PanelProveedores_POExplorer_Load(object sender, EventArgs e)
        {
            List <int> intList = new List <int>();

            for (int index = 0; index < this.supplier.POList.Rows.Count; ++index)
            {
                DateTime dateTime = Convert.ToDateTime(this.supplier.POList.Rows[index]["Fecha de Compra"]);
                if (intList.IndexOf(dateTime.Year) == -1)
                {
                    intList.Add(dateTime.Year);
                }
            }
            foreach (int num in intList)
            {
                this.treeView1.Nodes.Add(new TreeNode(num.ToString(), 1, 2));
            }
            foreach (TreeNode node in this.treeView1.Nodes)
            {
                node.Nodes.Add(node.Text, "Enero", 0);
                node.Nodes.Add(node.Text, "Febrero", 0);
                node.Nodes.Add(node.Text, "Marzo", 0);
                node.Nodes.Add(node.Text, "Abril", 0);
                node.Nodes.Add(node.Text, "Mayo", 0);
                node.Nodes.Add(node.Text, "Junio", 0);
                node.Nodes.Add(node.Text, "Julio", 0);
                node.Nodes.Add(node.Text, "Agosto", 0);
                node.Nodes.Add(node.Text, "Septiembre", 0);
                node.Nodes.Add(node.Text, "Octubre", 0);
                node.Nodes.Add(node.Text, "Noviembre", 0);
                node.Nodes.Add(node.Text, "Diciembre", 0);
            }
            DataTable dataTable = this.supplier.POList.Copy();

            foreach (TreeNode node1 in this.treeView1.Nodes)
            {
                for (int index1 = 0; index1 < node1.Nodes.Count; ++index1)
                {
                    TreeNode node2 = node1.Nodes[index1];
                    for (int index2 = 0; index2 < dataTable.Rows.Count; ++index2)
                    {
                        DataRow  row      = dataTable.Rows[index2];
                        DateTime dateTime = Convert.ToDateTime(row["Fecha de Compra"]);
                        string   str      = Convert.ToBoolean(row["Estado de Pago"]) ? "Pagado" : "Pago pendiente";
                        if (dateTime.Year.ToString() == node2.Parent.Text)
                        {
                            TreeNode node3 = (TreeNode)null;
                            if (dateTime.Month == 1 && node2.Text == "Enero")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 2 && node2.Text == "Febrero")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 3 && node2.Text == "Marzo")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 4 && node2.Text == "Abril")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 5 && node2.Text == "Mayo")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 6 && node2.Text == "Junio")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 7 && node2.Text == "Julio")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 8 && node2.Text == "Agosto")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 9 && node2.Text == "Septiembre")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 10 && node2.Text == "Octubre")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 11 && node2.Text == "Noviembre")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            if (dateTime.Month == 12 && node2.Text == "Diciembre")
                            {
                                node3 = new TreeNode(row["ID_PO"].ToString() + ", Total=" + Convert.ToDouble(row["Total"]).ToString("n2") + ", " + str, 1, 1);
                            }
                            node1.ImageIndex         = 0;
                            node1.SelectedImageIndex = 0;
                            if (node3 != null)
                            {
                                node3.ForeColor = !Convert.ToBoolean(row["Estado de Pago"]) ? Color.Tomato : Color.LimeGreen;
                                node2.Nodes.Add(node3);
                                row.Delete();
                                dataTable.AcceptChanges();
                                --index2;
                            }
                        }
                    }
                    if (node2.Nodes.Count == 0)
                    {
                        node2.Remove();
                        --index1;
                    }
                }
            }
        }
Пример #45
0
    public bool SaveData(object obj, string prameter)
    {
        string updataStr = "select * from ChipRegisterList where ID=" + moduleTypeID;

        try
        {
            if (AddNew)
            {
                if (!IsRangeValidator())
                {
                    return(false);
                }
                DataTable inserTable = pDataIO.GetDataTable(updataStr, "ChipRegisterList");
                DataRow   dr         = inserTable.NewRow();
                dr[0] = -1;
                dr[1] = moduleTypeID;
                dr[2] = chipsetControl.Colum1TextConfig;
                dr[3] = chipsetControl.Colum2TextConfig;
                dr[4] = chipsetControl.Colum3TextConfig;
                dr[5] = chipsetControl.Colum4TextConfig;

                dr[7]  = chipsetControl.Colum5TextConfig;
                dr[8]  = chipsetControl.Colum6TextConfig;
                dr[6]  = chipsetControl.Colum7TextConfig;
                dr[9]  = chipsetControl.Colum8TextConfig;
                dr[10] = chipsetControl.Colum9TextConfig;
                inserTable.Rows.Add(dr);
                int result = pDataIO.UpdateWithProc("ChipRegisterList", inserTable, updataStr, logTracingString);
                if (result > 0)
                {
                    inserTable.AcceptChanges();
                    Response.Redirect("~/WebFiles/Chip/RegisterFormulaList.aspx?uId=" + moduleTypeID.Trim());
                }
                else
                {
                    pDataIO.AlertMsgShow("Update data fail!", Request.Url.ToString());
                }

                return(true);
            }
            else
            {
                if (!IsRangeValidator())
                {
                    FormulaSelfInforlist[0].EnableColum1Text = false;
                    FormulaSelfInforlist[0].EnableColum2Text = false;
                    FormulaSelfInforlist[0].EnableColum3Text = false;
                    FormulaSelfInforlist[0].EnableColum4Text = false;
                    FormulaSelfInforlist[0].EnableColum5Text = false;
                    FormulaSelfInforlist[0].EnableColum6Text = false;
                    FormulaSelfInforlist[0].EnableColum7Text = false;
                    FormulaSelfInforlist[0].EnableColum8Text = false;
                    FormulaSelfInforlist[0].EnableColum9Text = false;
                    return(false);
                }
                if (rowCount != 1)
                {
                    return(false);
                }
                else
                {
                    for (byte j = 0; j < FormulaSelfInforlist.Length; j++)
                    {
                        mydt.Rows[0]["ItemName"]     = FormulaSelfInforlist[j].Colum1TextConfig;
                        mydt.Rows[0]["WriteFormula"] = FormulaSelfInforlist[j].Colum2TextConfig;
                        mydt.Rows[0]["AnalogueUnit"] = FormulaSelfInforlist[j].Colum3TextConfig;
                        mydt.Rows[0]["ReadFormula"]  = FormulaSelfInforlist[j].Colum4TextConfig;

                        mydt.Rows[0]["EndBit"]     = FormulaSelfInforlist[j].Colum7TextConfig;
                        mydt.Rows[0]["Address"]    = FormulaSelfInforlist[j].Colum5TextConfig;
                        mydt.Rows[0]["StartBit"]   = FormulaSelfInforlist[j].Colum6TextConfig;
                        mydt.Rows[0]["UnitLength"] = FormulaSelfInforlist[j].Colum8TextConfig;
                        mydt.Rows[0]["ChipLine"]   = FormulaSelfInforlist[j].Colum9TextConfig;
                    }
                    int result = pDataIO.UpdateWithProc("ChipRegisterList", mydt, updataStr, logTracingString);
                    if (result > 0)
                    {
                        mydt.AcceptChanges();
                    }
                    else
                    {
                        pDataIO.AlertMsgShow("Update data fail!");
                    }
                    for (byte i = 0; i < FormulaSelfInforlist.Length; i++)
                    {
                        FormulaSelfInforlist[i].EnableColum1Text = false;
                        FormulaSelfInforlist[i].EnableColum2Text = false;
                        FormulaSelfInforlist[i].EnableColum3Text = false;
                        FormulaSelfInforlist[i].EnableColum4Text = false;

                        FormulaSelfInforlist[i].EnableColum5Text = false;
                        FormulaSelfInforlist[i].EnableColum6Text = false;
                        FormulaSelfInforlist[i].EnableColum7Text = false;
                        FormulaSelfInforlist[i].EnableColum8Text = false;
                        FormulaSelfInforlist[i].EnableColum9Text = false;
                    }
                    return(true);
                }
            }
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
    }
Пример #46
0
        public void MultipleResultSetsTest()
        {
            DataTable dt1 = new DataTable("test2");
            dt1.Columns.Add("x", typeof(string));
            dt1.Rows.Add(new object[] { "test" });
            dt1.Rows.Add(new object[] { "test1" });
            dt1.AcceptChanges();

            DataTable[] collection = new DataTable[] { _dt, dt1 };

            DataTableReader reader = new DataTableReader(collection);
            try
            {
                int i = 0;
                do
                {
                    while (reader.Read())
                        i++;
                } while (reader.NextResult());

                Assert.Equal(5, i);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
            }
        }
Пример #47
0
        public void Load_RowStateUpsertUnchangedEqualVal()
        {
            localSetup();
            DataTable dtLoad = new DataTable("LoadRowStateChanges");
            dtLoad.Columns.Add("id", typeof(int));
            dtLoad.Columns.Add("name", typeof(string));
            dtLoad.PrimaryKey = new DataColumn[] { dtLoad.Columns["id"] };
            dtLoad.Rows.Add(new object[] { 1, "mono 1" });
            dtLoad.AcceptChanges();
            DataTableReader dtr = _dt.CreateDataReader();
            DataRowAction[] dra = new DataRowAction[] {
                DataRowAction.Nothing,// REAL action
				DataRowAction.Nothing,// dummy  
				DataRowAction.Nothing,// dummy  
				DataRowAction.Nothing,// dummy  
				DataRowAction.Nothing};// dummy  
            rowActionInit(dra);
            dtLoad.Load(dtr, LoadOption.Upsert);
            rowActionEnd();
            Assert.Equal("mono 1", dtLoad.Rows[0][1, DataRowVersion.Current]);
            Assert.Equal("mono 1", dtLoad.Rows[0][1, DataRowVersion.Original]);
            Assert.Equal(DataRowState.Unchanged, dtLoad.Rows[0].RowState);
        }
Пример #48
0
        private void MakeDummyTable()
        {
            // Create a new Table
            _dataSet = new DataSet();
            _dummyTable = new DataTable("DummyTable");
            DataColumn column;
            DataRow row;

            // Create new DataColumn, set DataType, 
            // ColumnName and add to Table.
            column = new DataColumn();
            column.DataType = typeof(int);
            column.ColumnName = "id";
            column.Unique = true;
            // Add the Column to the DataColumnCollection.
            _dummyTable.Columns.Add(column);

            // Create second column
            column = new DataColumn();
            column.DataType = typeof(string);
            column.ColumnName = "DummyItem";
            column.AutoIncrement = false;
            column.Caption = "DummyItem";
            column.Unique = false;
            // Add the column to the table
            _dummyTable.Columns.Add(column);

            _dataSet.Tables.Add(_dummyTable);

            // Create three new DataRow objects and add 
            // them to the DataTable
            for (int i = 0; i <= 2; i++)
            {
                row = _dummyTable.NewRow();
                row["id"] = i + 1;
                row["DummyItem"] = "DummyItem " + (i + 1);
                _dummyTable.Rows.Add(row);
            }

            DataRow row1 = _dummyTable.Rows[1];
            _dummyTable.AcceptChanges();
            row1.BeginEdit();
            row1[1] = "Changed_DummyItem " + 2;
            row1.EndEdit();
        }
Пример #49
0
 private void localSetup()
 {
     _ds = new DataSet("test");
     _dt1 = new DataTable("test1");
     _dt1.Columns.Add("id1", typeof(int));
     _dt1.Columns.Add("name1", typeof(string));
     //dt1.PrimaryKey = new DataColumn[] { dt1.Columns["id"] };
     _dt1.Rows.Add(new object[] { 1, "mono 1" });
     _dt1.Rows.Add(new object[] { 2, "mono 2" });
     _dt1.Rows.Add(new object[] { 3, "mono 3" });
     _dt1.AcceptChanges();
     _dt2 = new DataTable("test2");
     _dt2.Columns.Add("id2", typeof(int));
     _dt2.Columns.Add("name2", typeof(string));
     _dt2.Columns.Add("name3", typeof(string));
     //dt2.PrimaryKey = new DataColumn[] { dt2.Columns["id"] };
     _dt2.Rows.Add(new object[] { 4, "mono 4", "four" });
     _dt2.Rows.Add(new object[] { 5, "mono 5", "five" });
     _dt2.Rows.Add(new object[] { 6, "mono 6", "six" });
     _dt2.AcceptChanges();
     _ds.Tables.Add(_dt1);
     _ds.Tables.Add(_dt2);
     _ds.AcceptChanges();
 }
Пример #50
0
        public void AcceptChanges()
        {
            _evProp = null;
            DataTable dt = new DataTable();
            IBindingList list = dt.DefaultView;
            list.ListChanged += new ListChangedEventHandler(dv_ListChanged);
            dt.Columns.Add("test", typeof(int));
            dt.Rows.Add(new object[] { 10 });
            dt.Rows.Add(new object[] { 20 });
            // ListChangedType.Reset
            dt.AcceptChanges();

            Assert.Equal(true, _evProp != null);
            // AcceptChanges - should emit ListChangedType.Reset
            Assert.Equal(ListChangedType.Reset, _evProp.lstType);
        }
Пример #51
0
 public void RowVersion1()
 {
     // I guess we could write better tests.
     DataTable dt = new DataTable("table");
     dt.Columns.Add("col");
     dt.Rows.Add(new object[] { 1 });
     DataView dv = new DataView(dt);
     DataRowView drv = dv.AddNew();
     Assert.Equal(DataRowVersion.Current, drv.RowVersion);
     Assert.Equal(DataRowVersion.Current, dv[0].RowVersion);
     drv["col"] = "mod";
     Assert.Equal(DataRowVersion.Current, drv.RowVersion);
     Assert.Equal(DataRowVersion.Current, dv[0].RowVersion);
     dt.AcceptChanges();
     Assert.Equal(DataRowVersion.Current, drv.RowVersion);
     Assert.Equal(DataRowVersion.Current, dv[0].RowVersion);
     drv.EndEdit();
     dv[0].EndEdit();
     Assert.Equal(DataRowVersion.Current, drv.RowVersion);
     Assert.Equal(DataRowVersion.Current, dv[0].RowVersion);
 }
Пример #52
0
 private DataTable setupRowState()
 {
     DataTable tbl = new DataTable("LoadRowStateChanges");
     tbl.RowChanged += new DataRowChangeEventHandler(dtLoad_RowChanged);
     tbl.RowChanging += new DataRowChangeEventHandler(dtLoad_RowChanging);
     tbl.Columns.Add("id", typeof(int));
     tbl.Columns.Add("name", typeof(string));
     tbl.PrimaryKey = new DataColumn[] { tbl.Columns["id"] };
     tbl.Rows.Add(new object[] { 1, "RowState 1" });
     tbl.Rows.Add(new object[] { 2, "RowState 2" });
     tbl.Rows.Add(new object[] { 3, "RowState 3" });
     tbl.AcceptChanges();
     // Update Table with following changes: Row0 unmodified, 
     // Row1 modified, Row2 deleted, Row3 added, Row4 not-present.
     tbl.Rows[1]["name"] = "Modify 2";
     tbl.Rows[2].Delete();
     DataRow row = tbl.NewRow();
     row["id"] = 4;
     row["name"] = "Add 4";
     tbl.Rows.Add(row);
     return (tbl);
 }
Пример #53
0
 public void ListChangeOnSetItem()
 {
     DataTable dt = new DataTable("table");
     dt.Columns.Add("col1");
     dt.Columns.Add("col2");
     dt.Columns.Add("col3");
     dt.Rows.Add(new object[] { 1, 2, 3 });
     dt.AcceptChanges();
     DataView dv = new DataView(dt);
     dv.ListChanged += new ListChangedEventHandler(OnChange);
     dv[0]["col1"] = 4;
 }
Пример #54
0
        public void ToTableTest_DataValidity()
        {
            DataTable table = new DataTable();
            table.Columns.Add("col1", typeof(int));
            table.Columns.Add("col2", typeof(int));
            table.Columns.Add("col3", typeof(int));

            for (int i = 0; i < 5; ++i)
            {
                table.Rows.Add(new object[] { i, i + 1, i + 2 });
                table.Rows.Add(new object[] { i, i + 1, i + 2 });
            }

            table.AcceptChanges();
            DataView view = new DataView(table);
            try
            {
                DataTable newTable = view.ToTable(false, null);
            }
            catch (ArgumentNullException e)
            {
                // Never premise English.
                //Assert.Equal ("'columnNames' argument cannot be null." + Environment.NewLine + 
                //		"Parameter name: columnNames", e.Message, "#1");
            }
            DataTable newTable1 = view.ToTable(false, new string[] { });
            Assert.Equal(10, newTable1.Rows.Count);

            newTable1 = view.ToTable(true, new string[] { });
            Assert.Equal(3, newTable1.Columns.Count);
            Assert.Equal(5, newTable1.Rows.Count);

            table.Rows.Add(new object[] { 1, 100, 100 });

            newTable1 = view.ToTable(true, new string[] { });
            Assert.Equal(3, newTable1.Columns.Count);
            Assert.Equal(6, newTable1.Rows.Count);

            newTable1 = view.ToTable(true, new string[] { "col1" });
            Assert.Equal(1, newTable1.Columns.Count);
            Assert.Equal(5, newTable1.Rows.Count);

            newTable1 = view.ToTable(true, new string[] { "col2", "col3" });
            Assert.Equal(2, newTable1.Columns.Count);
            Assert.Equal(6, newTable1.Rows.Count);

            for (int i = 0; i < newTable1.Rows.Count; ++i)
                Assert.Equal(DataRowState.Added, newTable1.Rows[i].RowState);

            view = new DataView(table, "col1>1", "col1 asc, col2 desc", DataViewRowState.Added);
            Assert.Equal(0, view.Count);

            newTable1 = view.ToTable(false, new string[] { "col1", "col3" });
            Assert.Equal(0, newTable1.Rows.Count);

            table.Rows.Add(new object[] { 10, 1, 1 });
            table.Rows.Add(new object[] { 10, 1, 3 });
            table.Rows.Add(new object[] { 10, 1, 2 });

            Assert.Equal(3, view.Count);
            view.Sort = "col1 asc, col2 asc, col3 desc";
            newTable1 = view.ToTable(true, new string[] { "col1", "col3" });
            Assert.Equal(3, newTable1.Rows.Count);
            Assert.Equal(3, newTable1.Rows[0][1]);
            Assert.Equal(2, newTable1.Rows[1][1]);
            Assert.Equal(1, newTable1.Rows[2][1]);
        }
Пример #55
0
        public void Load_RowStateChangesDefaultDelete()
        {
            localSetup();
            DataTable dtLoad = new DataTable("LoadRowStateChanges");
            dtLoad.Columns.Add("id", typeof(int));
            dtLoad.Columns.Add("name", typeof(string));
            dtLoad.PrimaryKey = new DataColumn[] { dtLoad.Columns["id"] };
            dtLoad.Rows.Add(new object[] { 1, "RowState 1" });
            dtLoad.Rows.Add(new object[] { 2, "RowState 2" });
            dtLoad.Rows.Add(new object[] { 3, "RowState 3" });
            dtLoad.AcceptChanges();
            dtLoad.Rows[2].Delete();
            DataTableReader dtr = _dt.CreateDataReader();
            dtLoad.Load(dtr);

            try
            {
                Assert.Equal(" ", dtLoad.Rows[2][1, DataRowVersion.Current]);
                Assert.False(true);
            }
            catch (VersionNotFoundException)
            {
            }
        }
Пример #56
0
        public void Bug18898()
        {
            var table = new DataTable();
            table.Columns.Add("col1");
            table.Columns.Add("col2");

            table.Rows.Add("1", "2");
            table.Rows.Add("4", "3");

            table.AcceptChanges();

            table.Rows.Add("5", "6");

            DataView dv = new DataView(table, string.Empty, string.Empty, DataViewRowState.Added);
            dv.AllowNew = true;
            var new_row = dv.AddNew();
            new_row[0] = "7";
            new_row[1] = "8";

            var another_new_row = dv.AddNew();
            another_new_row[0] = "9";
            another_new_row[1] = "10";

            Assert.Equal(dv[2][0], "9");

            //This should not throw a System.Data.VersionNotFoundException: "There is no Proposed data to accces"
            Assert.Equal(dv[1][0], "7");
        }
Пример #57
0
        public void Delete()
        {
            DataTable myTable = new DataTable("myTable");
            DataColumn dc = new DataColumn("Id", typeof(int));
            dc.Unique = true;
            myTable.Columns.Add(dc);
            myTable.Rows.Add(new object[] { 1 });
            myTable.Rows.Add(new object[] { 2 });
            myTable.Rows.Add(new object[] { 3 });
            myTable.AcceptChanges();

            DataRow myRow = myTable.Rows[0];
            myRow.Delete();

            // Delete1
            Assert.Equal(DataRowState.Deleted, myRow.RowState);

            // Delete2
            myTable.AcceptChanges();
            Assert.Equal(DataRowState.Detached, myRow.RowState);
        }
Пример #58
0
        public void HasVersion_ByDataRowVersion()
        {
            DataTable t = new DataTable("atable");
            t.Columns.Add("id", typeof(int));
            t.Columns.Add("name", typeof(string));
            t.Columns[0].DefaultValue = 1;
            t.Columns[1].DefaultValue = "something";

            // row r is detached
            DataRow r = t.NewRow();

            // HasVersion Test #10
            Assert.Equal(false, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #11
            Assert.Equal(false, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #12
            Assert.Equal(true, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #13
            Assert.Equal(true, r.HasVersion(DataRowVersion.Proposed));

            r[0] = 4;
            r[1] = "four";

            // HasVersion Test #20
            Assert.Equal(false, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #21
            Assert.Equal(false, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #22
            Assert.Equal(true, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #23
            Assert.Equal(true, r.HasVersion(DataRowVersion.Proposed));

            t.Rows.Add(r);
            // now it is "added"

            // HasVersion Test #30
            Assert.Equal(true, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #31
            Assert.Equal(false, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #32
            Assert.Equal(true, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #33
            Assert.Equal(false, r.HasVersion(DataRowVersion.Proposed));

            t.AcceptChanges();
            // now it is "unchanged"

            // HasVersion Test #40
            Assert.Equal(true, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #41
            Assert.Equal(true, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #42
            Assert.Equal(true, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #43
            Assert.Equal(false, r.HasVersion(DataRowVersion.Proposed));

            r.BeginEdit();
            r[1] = "newvalue";

            // HasVersion Test #50
            Assert.Equal(true, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #51
            Assert.Equal(true, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #52
            Assert.Equal(true, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #53
            Assert.Equal(true, r.HasVersion(DataRowVersion.Proposed));

            r.EndEdit();
            // now it is "modified"
            // HasVersion Test #60
            Assert.Equal(true, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #61
            Assert.Equal(true, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #62
            Assert.Equal(true, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #63
            Assert.Equal(false, r.HasVersion(DataRowVersion.Proposed));

            // this or t.AcceptChanges
            r.AcceptChanges();
            // now it is "unchanged" again
            // HasVersion Test #70
            Assert.Equal(true, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #71
            Assert.Equal(true, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #72
            Assert.Equal(true, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #73
            Assert.Equal(false, r.HasVersion(DataRowVersion.Proposed));

            r.Delete();
            // now it is "deleted"

            // HasVersion Test #80
            Assert.Equal(false, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #81
            Assert.Equal(true, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #82
            Assert.Equal(false, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #83
            Assert.Equal(false, r.HasVersion(DataRowVersion.Proposed));

            r.AcceptChanges();
            // back to detached
            // HasVersion Test #90
            Assert.Equal(false, r.HasVersion(DataRowVersion.Current));

            // HasVersion Test #91
            Assert.Equal(false, r.HasVersion(DataRowVersion.Original));

            // HasVersion Test #92
            Assert.Equal(false, r.HasVersion(DataRowVersion.Default));

            // HasVersion Test #93
            Assert.Equal(false, r.HasVersion(DataRowVersion.Proposed));
        }
Пример #59
-1
        public void CloneCopyTest()
        {
            DataTable table = new DataTable();
            table.TableName = "Table#1";
            DataTable table1 = new DataTable();
            table1.TableName = "Table#2";

            table.AcceptChanges();

            DataSet set = new DataSet("Data Set#1");
            set.DataSetName = "Dataset#1";
            set.Tables.Add(table);
            set.Tables.Add(table1);

            DataColumn col = new DataColumn();
            col.ColumnName = "Id";
            col.DataType = typeof(int);
            table.Columns.Add(col);
            UniqueConstraint uc = new UniqueConstraint("UK1", table.Columns[0]);
            table.Constraints.Add(uc);

            col = new DataColumn();
            col.ColumnName = "Id";
            col.DataType = typeof(int);
            table1.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "Name";
            col.DataType = typeof(string);
            table.Columns.Add(col);

            col = new DataColumn();
            col.ColumnName = "Name";
            col.DataType = typeof(string);
            table1.Columns.Add(col);
            DataRow row = table.NewRow();
            row["Id"] = 147;
            row["name"] = "Abc";
            row.RowError = "Error#1";
            table.Rows.Add(row);

            row = table.NewRow();
            row["Id"] = 47;
            row["name"] = "Efg";
            table.Rows.Add(row);
            table.AcceptChanges();

            table.CaseSensitive = true;
            table1.CaseSensitive = true;
            table.MinimumCapacity = 100;
            table.Prefix = "PrefixNo:1";
            table.Namespace = "Namespace#1";
            table.DisplayExpression = "Id / Name + (Id * Id)";
            DataColumn[] colArray = { table.Columns[0] };
            table.PrimaryKey = colArray;
            table.ExtendedProperties.Add("TimeStamp", DateTime.Now);

            row = table1.NewRow();
            row["Name"] = "Abc";
            row["Id"] = 147;
            table1.Rows.Add(row);

            row = table1.NewRow();
            row["Id"] = 47;
            row["Name"] = "Efg";
            table1.Rows.Add(row);

            DataRelation dr = new DataRelation("DR", table.Columns[0], table1.Columns[0]);
            set.Relations.Add(dr);

            //Testing properties of clone
            DataTable cloneTable = table.Clone();
            Assert.True(cloneTable.CaseSensitive);
            Assert.Equal(0, cloneTable.ChildRelations.Count);
            Assert.Equal(0, cloneTable.ParentRelations.Count);
            Assert.Equal(2, cloneTable.Columns.Count);
            Assert.Equal(1, cloneTable.Constraints.Count);
            Assert.Equal("Id / Name + (Id * Id)", cloneTable.DisplayExpression);
            Assert.Equal(1, cloneTable.ExtendedProperties.Count);
            Assert.False(cloneTable.HasErrors);
            Assert.Equal(100, cloneTable.MinimumCapacity);
            Assert.Equal("Namespace#1", cloneTable.Namespace);
            Assert.Equal("PrefixNo:1", cloneTable.Prefix);
            Assert.Equal("Id", cloneTable.PrimaryKey[0].ColumnName);
            Assert.Equal(0, cloneTable.Rows.Count);
            Assert.Equal("Table#1", cloneTable.TableName);

            //Testing properties of copy
            DataTable copyTable = table.Copy();
            Assert.True(copyTable.CaseSensitive);
            Assert.Equal(0, copyTable.ChildRelations.Count);
            Assert.Equal(0, copyTable.ParentRelations.Count);
            Assert.Equal(2, copyTable.Columns.Count);
            Assert.Equal(1, copyTable.Constraints.Count);
            Assert.Equal("Id / Name + (Id * Id)", copyTable.DisplayExpression);
            Assert.Equal(1, copyTable.ExtendedProperties.Count);
            Assert.True(copyTable.HasErrors);
            Assert.Equal(100, copyTable.MinimumCapacity);
            Assert.Equal("Namespace#1", copyTable.Namespace);
            Assert.Equal("PrefixNo:1", copyTable.Prefix);
            Assert.Equal("Id", copyTable.PrimaryKey[0].ColumnName);
            Assert.Equal(2, copyTable.Rows.Count);
            Assert.Equal("Table#1", copyTable.TableName);
        }
Пример #60
-1
        public void Load_RowStateUpsertDuplicateKey1()
        {
            localSetup();
            _dt.Rows.Add(new object[] { 4, "mono 4" });
            DataTable dtLoad = new DataTable("LoadRowStateChanges");
            dtLoad.Columns.Add("id", typeof(int));
            dtLoad.Columns.Add("name", typeof(string));
            dtLoad.PrimaryKey = new DataColumn[] { dtLoad.Columns["id"] };
            dtLoad.Rows.Add(new object[] { 1, "RowState 1" });
            dtLoad.Rows.Add(new object[] { 2, "RowState 2" });
            dtLoad.Rows.Add(new object[] { 3, "RowState 3" });
            dtLoad.AcceptChanges();
            dtLoad.Rows[2].Delete();
            DataTableReader dtr = _dt.CreateDataReader();
            dtLoad.Load(dtr, LoadOption.Upsert);
            dtLoad.Rows[3][1] = "NEWVAL";
            Assert.Equal(DataRowState.Deleted, dtLoad.Rows[2].RowState);
            Assert.Equal(3, dtLoad.Rows[2][0, DataRowVersion.Original]);
            Assert.Equal("RowState 3", dtLoad.Rows[2][1, DataRowVersion.Original]);
            Assert.Equal(DataRowState.Added, dtLoad.Rows[3].RowState);
            Assert.Equal(3, dtLoad.Rows[3][0, DataRowVersion.Current]);
            Assert.Equal("NEWVAL", dtLoad.Rows[3][1, DataRowVersion.Current]);
            Assert.Equal(DataRowState.Added, dtLoad.Rows[4].RowState);
            Assert.Equal(4, dtLoad.Rows[4][0, DataRowVersion.Current]);
            Assert.Equal("mono 4", dtLoad.Rows[4][1, DataRowVersion.Current]);

            dtLoad.AcceptChanges();

            Assert.Equal(DataRowState.Unchanged, dtLoad.Rows[2].RowState);
            Assert.Equal(3, dtLoad.Rows[2][0, DataRowVersion.Current]);
            Assert.Equal("NEWVAL", dtLoad.Rows[2][1, DataRowVersion.Current]);
            Assert.Equal(DataRowState.Unchanged, dtLoad.Rows[3].RowState);
            Assert.Equal(4, dtLoad.Rows[3][0, DataRowVersion.Current]);
            Assert.Equal("mono 4", dtLoad.Rows[3][1, DataRowVersion.Current]);
        }