LoadDataRow() public method

Finds and updates a specific row. If no matching row is found, a new row is created using the given values.
public LoadDataRow ( object values, LoadOption loadOption ) : DataRow
values object
loadOption LoadOption
return DataRow
        public static string aboutList()
        {
            StringBuilder strTxt = new StringBuilder();
            DataTable tbl = new DataTable();
            tbl.Columns.Add("Title", typeof(string));
            tbl.Columns.Add("Url", typeof(string));
            object[] aValues = { "公司简介", "About.aspx" };
            tbl.LoadDataRow(aValues, true);
            object[] aValues1 = { "招聘信息", "Jobs.aspx" };
            tbl.LoadDataRow(aValues1, true);
            object[] aValues2 = { "站点地图", "SiteMap.aspx" };
            tbl.LoadDataRow(aValues2, true);
            object[] aValues3 = { "联系我们", "ContactInfo.aspx" };
            tbl.LoadDataRow(aValues3, true);

            if (tbl.Rows.Count > 0)
            {
                strTxt.Append("<dl>");
                for (int j = 0; j < tbl.Rows.Count; j++)
                {
                    DataRow dr2 = tbl.Rows[j];
                    strTxt.Append("<dd style=\"background-color: rgb(239,239,239); height: 26px;\">");
                    strTxt.Append("<a class=\"channelClass01\" href=\""+ dr2["Url"].ToString() +"\" style=\"position: relative;top: 5px; left: 15px;\">" + dr2["Title"].ToString() + "</a>");
                    strTxt.Append("</dd>");
                }
                strTxt.Append("</dl>");
            }
            else
                strTxt.Append("暂无栏目!");
            return strTxt.ToString();
        }
 public static DataTable CommasInDataDataTable()
 {
     DataTable dataTable = new DataTable();
     dataTable.Columns.Add("First");
     dataTable.Columns.Add("Second");
     dataTable.Columns.Add("Third");
     dataTable.LoadDataRow(new object[] { "a,a", "b,b", "c,c" }, false);
     dataTable.LoadDataRow(new object[] { "a1,a1", "b1,b1", "c1,c1" }, false);
     return dataTable;
 }
Beispiel #3
0
        static void Main(string[] args)
        {
            DataTable cave = new DataTable("Cave"); // création de la table "Cave" (vide pour l'instant)

            DataColumn id = new DataColumn("ID");
            id.DataType = typeof(int);
            id.AutoIncrement = true; // active l'autoincrémentation de la colonne
            id.AutoIncrementSeed = 1; // valeur de départ pour l'autoincrémentation
            id.AutoIncrementStep = 1; // pas pour l'autoincrémentation
            cave.Columns.Add(id);
            cave.PrimaryKey = new DataColumn[] { id }; // désignation de la colonne "ID" comme clé primaire de la table

            DataColumn vin = new DataColumn("Vin"); // création d'une colonne "Vin"
            vin.DataType = typeof(string); // le type de données est string par défaut, cette ligne est donc optionelle
            vin.Unique = true; // détermine si les valeurs de la colonnes doivent être uniques (false par défaut)
            vin.AllowDBNull = false; // détermine si la colonne accepte les valeurs NULL (true par défaut)
            vin.Caption = "Vin"; // nom que portera la colonne dans la représentation graphique (par défaut, c'est le nom de la colonne spécifié lors de la déclaration)
            cave.Columns.Add(vin); // la colonne "Vin" est ajoutée à la table "Cave"

            DataColumn annee = new DataColumn("Annee", typeof(int)); // on peut utiliser le constructeur à 2 paramètres pour déclarer une nouvelle colonne tout en spécifiant son type
            annee.AllowDBNull = false;
            annee.Caption = "Année";
            cave.Columns.Add(annee);

            DataColumn marque = new DataColumn("Marque");
            marque.MaxLength = 35;  // détermine la taille maximale dans le cas d'un string (-1 par défaut, càd illimité)
            marque.AllowDBNull = false;
            cave.Columns.Add(marque);

            // la colonne suivante est une colonne dérivée des colonnes "Marque" et "Année"
            DataColumn marqueEtAnnee = new DataColumn("MarqueEtAnnee");
            marqueEtAnnee.MaxLength = 40;
            marqueEtAnnee.Expression = "Annee + ' ' + Marque"; // la propriété "Expression" permet de concaténer les valeurs de plusieurs colonnes
            marqueEtAnnee.Caption = "Marque et Année";
            cave.Columns.Add(marqueEtAnnee);

            // remplissage de la table
            DataRow newCave = cave.NewRow(); // création de la ligne à insérer
            newCave["Vin"] = "Beaujolais";
            newCave["Marque"] = "Grand Cru";
            newCave["Annee"] = 1982;
            cave.Rows.Add(newCave); // ajout de la ligne à la table "Cave"

            cave.LoadDataRow(new object[] { null, "Bourgogne", 2012, "Prix 2012" }, true); // une autre méthode d'ajout de lignes
            cave.LoadDataRow(new object[] { null, "Saint-Emilion", 1983, "Cuvée Prestige" }, true);
            cave.LoadDataRow(new object[] { null, "Pommard", 1959, "Clos Blanc" }, true);

            printTable(cave);
        }
        public void It_should_return_the_values_in_the_range()
        {
            _DataTable.LoadDataRow(new object[] { "Value-1", "Value-2" }, true);

            var expected = new[]
            {
                _DataTable.LoadDataRow(new object[] { "Value-3", "Value-4" }, true),
                _DataTable.LoadDataRow(new object[] { "Value-5", "Value-6" }, true),
                _DataTable.LoadDataRow(new object[] { "Value-7", "Value-8" }, true)
            };

            var rows = _DataTable.GetRows(((0, 1), (0, 3)));

            Assert.IsTrue(rows.SequenceEqual(expected, DataRowComparer.Default));
        }
Beispiel #5
0
        public static DataTable ListToDataTable(IList ResList)
        {
            DataTable TempDT = new DataTable();

            System.Reflection.PropertyInfo[] p = ResList[0].GetType().GetProperties();
            foreach (System.Reflection.PropertyInfo pi in p)
            {
                TempDT.Columns.Add(pi.Name, System.Type.GetType(pi.PropertyType.ToString()));
            }

            for (int i = 0; i < ResList.Count; i++)
            {
                IList TempList = new ArrayList();
                foreach (System.Reflection.PropertyInfo pi in p)
                {
                    object oo = pi.GetValue(ResList[i], null);
                    TempList.Add(oo);
                }

                object[] itm = new object[p.Length];
                for (int j = 0; j < TempList.Count; j++)
                {
                    itm.SetValue(TempList[j], j);
                }
                TempDT.LoadDataRow(itm, true);
            }
            return TempDT;
        }
Beispiel #6
0
 public static DataTable ConverDataReaderToDataTable(IDataReader reader)
 {
     if (reader == null)
     {
         return null;
     }
     DataTable table = new DataTable
     {
         Locale = CultureInfo.InvariantCulture
     };
     int fieldCount = reader.FieldCount;
     for (int i = 0; i < fieldCount; i++)
     {
         table.Columns.Add(reader.GetName(i), reader.GetFieldType(i));
     }
     table.BeginLoadData();
     object[] values = new object[fieldCount];
     while (reader.Read())
     {
         reader.GetValues(values);
         table.LoadDataRow(values, true);
     }
     table.EndLoadData();
     return table;
 }
Beispiel #7
0
		private static DataTable GenerateLargeInputTable()
		{
			var sourceTable = new DataTable();
			sourceTable.Columns.Add("BeginTime", typeof(DateTime));
			sourceTable.Columns.Add("EndTime", typeof(DateTime));
			sourceTable.Columns.Add("TravelTypeId", typeof(short));

			for (var date = new DateTime(1000, 1, 1); date.Year <= 3000; date = date.AddDays(3))
			{
				sourceTable.LoadDataRow(new object[] { date.AddHours(8.0), date.AddHours(10.0), (short)0 }, LoadOption.OverwriteChanges);
				sourceTable.LoadDataRow(new object[] { date.AddHours(17.0), date.AddHours(19.0), (short)1 }, LoadOption.OverwriteChanges);
				sourceTable.LoadDataRow(new object[] { date.AddHours((24.0 * 2) + 17.0), date.AddHours((24.0 * 2) + 19.0), (short)2 }, LoadOption.OverwriteChanges);
			}

			return sourceTable;
		}
Beispiel #8
0
        public static DataTable ConvertDataReaderToDataTable(SqlDataReader reader)
        {
            try
            {
                DataTable objDataTable  = new DataTable();
                int       intFieldCount = reader.FieldCount;
                for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
                {
                    objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter));
                }
                objDataTable.BeginLoadData();

                object[] objValues = new object[intFieldCount];
                while (reader.Read())
                {
                    reader.GetValues(objValues);
                    objDataTable.LoadDataRow(objValues, true);
                }
                reader.Close();
                objDataTable.EndLoadData();

                return(objDataTable);
            }
            catch (Exception ex)
            {
                throw new Exception("转换出错!", ex);
            }
        }
Beispiel #9
0
        public static DataTable ConvertDataReaderToDataTable(DbDataReader reader)
        {
            try
            {
                DataTable table = new DataTable();
                int fieldCount = reader.FieldCount;
                for (int fieldIndex = 0; fieldIndex < fieldCount; ++fieldIndex)
                {
                    table.Columns.Add(reader.GetName(fieldIndex), reader.GetFieldType(fieldIndex));
                }

                table.BeginLoadData();

                object[] rowValues = new object[fieldCount];
                while (reader.Read())
                {
                    reader.GetValues(rowValues);
                    table.LoadDataRow(rowValues, true);
                }
                reader.Close();
                table.EndLoadData();

                return table;

            }
            catch (Exception ex)
            {
                throw new Exception("DataReader转换为DataTable时出错!", ex);
            }
        }
Beispiel #10
0
        public static DataSet DataReaderToDataSet(IDataReader reader)
        {
            var ds = new DataSet();
            DataTable table;
            do
            {
                int fieldCount = reader.FieldCount;
                table = new DataTable();
                for (int i = 0; i < fieldCount; i++)
                {
                    table.Columns.Add(reader.GetName(i), reader.GetFieldType(i));
                }
                table.BeginLoadData();
                var values = new Object[fieldCount];
                while (reader.Read())
                {
                    reader.GetValues(values);
                    table.LoadDataRow(values, true);
                }
                table.EndLoadData();

                ds.Tables.Add(table);

            } while (reader.NextResult());
            reader.Close();
            return ds;
        }
Beispiel #11
0
        /// <summary> 
        /// 集合装换DataSet 
        /// </summary> 
        /// <param name="list">集合</param> 
        /// <returns></returns> 
        /// 2008-08-01 22:08 HPDV2806 
        public static DataSet ToDataSet(IList p_List)
        {
            DataSet result = new DataSet();
            DataTable _DataTable = new DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    _DataTable.Columns.Add(pi.Name, pi.PropertyType);
                }

                for (int i = 0; i < p_List.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(p_List[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true);
                }
            }
            result.Tables.Add(_DataTable);
            return result;
        }
Beispiel #12
0
        public static DataTable ToTable <T>(this IList <T> list)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            if (list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                var            t         = typeof(string);
                foreach (PropertyInfo pi in propertys)
                {
                    dt.Columns.Add(pi.Name, t);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return(dt);
        }
Beispiel #13
0
        private static DataTable getTable(string xmlTable_)
    {
      var doc = new System.Xml.XmlDocument();
      doc.LoadXml(xmlTable_);

      DataTable dt = new DataTable();

      foreach (XmlNode rowNode in doc.DocumentElement.SelectNodes("./Table/Rows/Row"))
      {
        if (dt.Columns.Count == 0)
        {
          foreach (XmlNode node in rowNode.SelectNodes("./string"))
            dt.Columns.Add(node.InnerText);
        }
        else
        {
          string[] vals = new string[dt.Columns.Count];
          XmlNodeList list = rowNode.SelectNodes("./string");

          for (int i = 0; i < list.Count; ++i)
            vals[i] = list[i].InnerText;
          dt.LoadDataRow(vals, true);
        }
      }

      return dt;

    }
Beispiel #14
0
 public static System.Data.DataTable ConverDataReaderToDataTable(System.Data.IDataReader reader)
 {
     System.Data.DataTable result;
     if (null == reader)
     {
         result = null;
     }
     else
     {
         System.Data.DataTable dataTable = new System.Data.DataTable();
         dataTable.Locale = CultureInfo.InvariantCulture;
         int fieldCount = reader.FieldCount;
         for (int i = 0; i < fieldCount; i++)
         {
             dataTable.Columns.Add(reader.GetName(i), reader.GetFieldType(i));
         }
         dataTable.BeginLoadData();
         object[] values = new object[fieldCount];
         while (reader.Read())
         {
             reader.GetValues(values);
             dataTable.LoadDataRow(values, true);
         }
         dataTable.EndLoadData();
         result = dataTable;
     }
     return(result);
 }
Beispiel #15
0
        /// <summary>
        /// 将集合类转换成DataTable
        /// </summary>
        /// <param name="list">集合</param>
        public static System.Data.DataTable ToDataTable(IList list)
        {
            System.Data.DataTable result = new System.Data.DataTable();
            if (list != null && list.Count > 0)
            {
                PropertyInfo[] propertys = list[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return(result);
        }
Beispiel #16
0
        public static DataTable DGVToTable(DataGridView dgv)
        {
            System.Data.DataTable table = new System.Data.DataTable();

            IEnumerable <DataGridViewColumn> cols = dgv.Columns.OfType <DataGridViewColumn>();

            cols = cols.Where(o => o.Visible);

            foreach (DataGridViewColumn col in cols)
            {
                table.Columns.Add(col.HeaderText, typeof(object), String.Empty);
            }

            System.Collections.ArrayList list = new System.Collections.ArrayList();

            foreach (DataGridViewRow row in dgv.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cols.Contains(cell.OwningColumn))
                    {
                        list.Add(cell.Value);
                    }
                }
                table.LoadDataRow(list.ToArray(), true);
                list.Clear();
            }
            table.TableName = dgv.Name;
            return(table);
        }
Beispiel #17
0
        private static DataTable CreateDataTable(_Worksheet xlWorksheet)
        {
            var dataTable     = new DataTable();
            var worksheetName = xlWorksheet.Name;

            dataTable.TableName = worksheetName;
            var xlRange    = xlWorksheet.UsedRange;
            var valueArray = (object[, ])xlRange.Value[XlRangeValueDataType.xlRangeValueDefault];

            for (var k = 1; k <= valueArray.GetLength(1); k++)
            {
                dataTable.Columns.Add(valueArray[1, k].ToString());
            }

            var singleDValue = new object[valueArray.GetLength(1)];

            for (var i = 2; i <= valueArray.GetLength(0); i++)
            {
                for (var j = 0; j < valueArray.GetLength(1); j++)
                {
                    singleDValue[j] = valueArray[i, j + 1];
                }

                dataTable.LoadDataRow(singleDValue, LoadOption.PreserveChanges);
            }

            return(dataTable);
        }
        public DataTable GetRecord()
        {
            FinesStyleInfoRequery finesStyleInfo = new FinesStyleInfoRequery();
            IList iList=finesStyleInfo.FinesInfoRequery(null);
            if (iList == null)
                return null;

            DataTable result = new DataTable();
            if (iList.Count > 0)
            {
                PropertyInfo[] propertys = iList[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }

                for (int i = 0; i < iList.Count; i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        object obj = pi.GetValue(iList[i], null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
            }
            return result;
        }
Beispiel #19
0
        private static DataTable ConvertToDataTable(object[] excelObjctData, string primaryKeyValue, string colsKeyValue)
        {
            Hashtable colsHash = ParseCols(colsKeyValue);

            DataTable dt = new DataTable();

            if (excelObjctData.Length > 0)
            {
                for (int i = 0; i < ((object[])excelObjctData[0]).Length; i++)
                {
                    dt.Columns.Add(ToTagName(i));
                }

                foreach (object[] objs in excelObjctData)
                {
                    if (objs[ToIndex(primaryKeyValue)] == null)
                    {
                        break;
                    }
                    dt.LoadDataRow(ParseColsType(objs, colsHash), true);

                }

                for (int i = 0; i < ((object[])excelObjctData[0]).Length; i++)
                {
                    if (!colsHash.ContainsKey(ToTagName(i)))
                    {
                        dt.Columns.Remove(ToTagName(i));
                    }
                }
            }
            return dt;
        }
Beispiel #20
0
 /// <summary>
 /// 讲list集合转换成datatable
 /// </summary>
 /// <param name="list"></param>
 /// <returns></returns>
 public static System.Data.DataTable ListToDataTable(IList list)
 {
     System.Data.DataTable result = new System.Data.DataTable();
     if (list.Count > 0)
     {
         PropertyInfo[] propertys = list[0].GetType().GetProperties();
         foreach (PropertyInfo pi in propertys)
         {
             //获取类型
             Type colType = pi.PropertyType;
             //当类型为Nullable<>时
             if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable <>)))
             {
                 colType = colType.GetGenericArguments()[0];
             }
             result.Columns.Add(pi.Name, colType);
         }
         for (int i = 0; i < list.Count; i++)
         {
             ArrayList tempList = new ArrayList();
             foreach (PropertyInfo pi in propertys)
             {
                 object obj = pi.GetValue(list[i], null);
                 tempList.Add(obj);
             }
             object[] array = tempList.ToArray();
             result.LoadDataRow(array, true);
         }
     }
     return(result);
 }
Beispiel #21
0
        public void load_from_excel_file(string path, int bufferSize, out float[] channel_2, out float[] timeCoordinate, out int count_channel_2)
        {
            var workbook = ExcelLibrary.SpreadSheet.Workbook.Load(path);
            var worksheet = workbook.Worksheets[0];
            var cells = worksheet.Cells;
            var dataTable = new DataTable("datatable");
            // добавить столбцы в таблицу
            dataTable.Columns.Add("force");
            dataTable.Columns.Add("time");
            // добавить строки в таблицу
            for (int rowIndex = cells.FirstRowIndex + 1; rowIndex <= cells.LastRowIndex; rowIndex++)
            {
                var values = new List<string>();
                foreach (var cell in cells.GetRow(rowIndex))
                {
                    values.Add(cell.Value.StringValue);
                }

                dataTable.LoadDataRow(values.ToArray(), true);
            }

            DataRow[] dr = dataTable.Select();
            channel_2 = new float[bufferSize];
            timeCoordinate = new float[bufferSize];
            count_channel_2 = 0;

            foreach (DataRow r in dr)
            {
                channel_2[count_channel_2] = Int16.Parse((string)r[0]);
                timeCoordinate[count_channel_2] = Single.Parse((string)r[1]);
                count_channel_2++;
            }
        }
Beispiel #22
0
        private void UpdateMe_Load(object sender, EventArgs e)
        {
            //WN8ExpectedGrid dd = new WN8ExpectedGrid();
            //dd.Show();

            WOTStatistics.Core.WOTHelper.AddToLog("########## WOT Statistics initializing");

            _updateServers.Add(1, "http://www.vbaddict.net:82/");

            oTableUpdate = new DataTable();

            oTableUpdate.Columns.Add("Short", System.Type.GetType("System.String"));
            oTableUpdate.Columns.Add("Name", System.Type.GetType("System.String"));
            oTableUpdate.Columns.Add("VersionLocal", System.Type.GetType("System.String"));
            oTableUpdate.Columns.Add("VersionServer", System.Type.GetType("System.String"));
            oTableUpdate.Columns.Add("Status", System.Type.GetType("System.String"));


            oTableUpdate.BeginLoadData();
            oTableUpdate.LoadDataRow(new object[] { "CheckVersion", "Server Connection" }, true);
            oTableUpdate.LoadDataRow(new object[] { "AppVersion", "Version", WOTStatistics.Core.UserSettings.AppVersion }, true);
            oTableUpdate.LoadDataRow(new object[] { "ReleaseNotes", "Release Notes", WOTStatistics.Core.UserSettings.LastReleaseNotes }, true);
            oTableUpdate.LoadDataRow(new object[] { "SettingsFileVersion", "Settings", WOTStatistics.Core.UserSettings.SettingsFileVersion }, true);
            oTableUpdate.LoadDataRow(new object[] { "Images", "Image Verification" }, true);
            oTableUpdate.LoadDataRow(new object[] { "TranslationFileVersion", "Translations", WOTStatistics.Core.UserSettings.TranslationFileVersion }, true);
            oTableUpdate.LoadDataRow(new object[] { "ScriptFileVersion", "Rating Formula", WOTStatistics.Core.UserSettings.ScriptFileVersion }, true);
            oTableUpdate.LoadDataRow(new object[] { "DossierVersion", "Dossier Decrypter", WOTStatistics.Core.UserSettings.DossierVersion }, true);
            oTableUpdate.LoadDataRow(new object[] { "WN8ExpectedVersion", "WN8 Expected Tank Values", WOTStatistics.Core.UserSettings.WN8ExpectedVersion }, true);
            //oTableUpdate.LoadDataRow(new object[] { "ActiveDossierUploaderVersion", "Active Dossier Uploader", WOTStatistics.Core.UserSettings.ActiveDossierUploaderVersion }, true);
            oTableUpdate.LoadDataRow(new object[] { "DBMain", "Database State" }, true);
            oTableUpdate.EndLoadData();


            //oStatus.SmallImages = imgStatus;
            //oStatus.Items.Clear();
            //oStatus.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("Fail", 0, 0));
            //oStatus.Items.Add(new DevExpress.XtraEditors.Controls.ImageComboBoxItem("Success", 1, 1));


            _workerThread = new BackgroundWorker()
            {
                WorkerSupportsCancellation = true
            };
            _workerThread.DoWork             += new DoWorkEventHandler(bgw_DoWork);
            _workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
            _workerThread.RunWorkerAsync();
        }
Beispiel #23
0
    public void Create(ConstructGen<double> candleData_, int openIndex_ = 0, int highIndex_ = 1, int lowIndex_ = 2, int closeIndex_ = 3, int setupLength_=9, int countdownLength_=13)
    {
      var dt = new DataTable();
      dt.Rows.Clear();
      dt.Columns.Clear();

      dt.Columns.Add("Date", typeof(DateTime));
      dt.Columns.Add("Open", typeof(double));
      dt.Columns.Add("High", typeof(double));
      dt.Columns.Add("Low", typeof(double));
      dt.Columns.Add("Close", typeof(double));
      dt.Columns.Add("Volume", typeof(double));

      ultraChart1.DataSource = dt;

      var closes = candleData_.GetColumnValuesAsDDC(closeIndex_);
      var range = closes.Data.Max() - closes.Data.Min();
      var cellHeight = range/10d;


      var setupStarts = DeMarkAnalysis.GetSetups(candleData_,openIndex_,highIndex_,lowIndex_,closeIndex_,setupLength_);
      DeMarkAnalysis.AddCountdowns(candleData_, setupStarts,openIndex_,highIndex_,lowIndex_,closeIndex_,setupLength_,countdownLength_);


      for (int i = 0; i < candleData_.Dates.Count; ++i)
      {
        var date = candleData_.Dates[i];

        var arr = candleData_.GetValues(date);
        dt.LoadDataRow(new object[]
        {
          date,
          arr[openIndex_],
          arr[highIndex_],
          arr[lowIndex_],
          arr[closeIndex_],
          0d
        }, true);

        foreach(var mark in setupStarts)
        {
          addAnnotations(date, mark, i, cellHeight, arr,openIndex_,highIndex_,lowIndex_,closeIndex_);
        }
      }

      EstablishDefaultTooltip(hash =>
      {
        int rowNumber = (int) hash["DATA_ROW"];

        return string.Format("{0} Open: {1}, High: {2}, Low: {3}, Close: {4}",
          ((DateTime) dt.Rows[rowNumber]["Date"]).ToString("dd-MMM-yyyy"),
          ((double) dt.Rows[rowNumber]["Open"]).ToString(CultureInfo.InvariantCulture),
          ((double)dt.Rows[rowNumber]["High"]).ToString(CultureInfo.InvariantCulture),
          ((double)dt.Rows[rowNumber]["Low"]).ToString(CultureInfo.InvariantCulture),
          ((double)dt.Rows[rowNumber]["Close"]).ToString(CultureInfo.InvariantCulture)
          ).Replace(",", System.Environment.NewLine);

      });
    }
        public static DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
        {
            FirstDataTable = FirstDataTable.Copy();
            FirstDataTable.TableName += " First";
            SecondDataTable = SecondDataTable.Copy();
            SecondDataTable.TableName += " Second";
            //Create Empty Table
            DataTable ResultDataTable = new DataTable("ResultDataTable");

            //use a Dataset to make use of a DataRelation object
            using (DataSet ds = new DataSet())
            {

                //Add tables
                ds.Tables.AddRange(new DataTable[] { FirstDataTable, SecondDataTable });

                //Get Columns for DataRelation
                DataColumn[] firstColumns = FirstDataTable.Columns.Cast<DataColumn>().ToArray();

                DataColumn[] secondColumns = SecondDataTable.Columns.Cast<DataColumn>().ToArray();

                //Create DataRelation
                DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
                ds.Relations.Add(r1);

                //DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
                //ds.Relations.Add(r2);

                //Create columns for return table
                List<DataColumn> PK = new List<DataColumn>();
                for (int i = 0; i < FirstDataTable.Columns.Count; i++)
                {
                    DataColumn newdc = ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
                    if (FirstDataTable.PrimaryKey.Contains(FirstDataTable.Columns[i]))
                        PK.Add(newdc);
                }
                ResultDataTable.PrimaryKey = PK.ToArray();
                //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.
                ResultDataTable.BeginLoadData();
                foreach (DataRow parentrow in FirstDataTable.Rows)
                {
                    DataRow[] childrows = parentrow.GetChildRows(r1);
                    if (childrows == null || childrows.Length == 0)
                        ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
                }

                ////If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.
                //foreach (DataRow parentrow in SecondDataTable.Rows)
                //{
                //    DataRow[] childrows = parentrow.GetChildRows(r2);
                //    if (childrows == null || childrows.Length == 0)
                //        ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
                //}
                ResultDataTable.EndLoadData();
            }
            return ResultDataTable;
        }
Beispiel #25
0
 public static DataTable ComplexDataTable()
 {
     DataTable dataTable = new DataTable();
     dataTable.Columns.Add("First Entry");
     dataTable.Columns.Add("2nd 'Entry'");
     dataTable.Columns.Add("3 \"Entry\"");
     dataTable.LoadDataRow(new object[] { "a'a a", "b\"b\"b", "c'c'c" }, false);
     return dataTable;
 }
Beispiel #26
0
 public static DataTable SimpleDataTable()
 {
     DataTable dataTable = new DataTable();
     dataTable.Columns.Add("First");
     dataTable.Columns.Add("2nd");
     dataTable.Columns.Add("3");
     dataTable.LoadDataRow(new object[] { "a", "b", "c" }, false);
     return dataTable;
 }
        public static DataSet ToDataSet(IList <T> p_List, params string[] p_PropertyName)//p_List被转换的对象,p_PropertyName想要获得属性
        {
            List <string> propertyNameList = new List <string>();

            if (p_PropertyName != null)
            {
                propertyNameList.AddRange(p_PropertyName);
            }
            DataSet result = new DataSet();

            System.Data.DataTable _DataTable = new System.Data.DataTable();
            if (p_List.Count > 0)
            {
                PropertyInfo[] propertys = p_List[0].GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)//添加属性
                {
                    if (propertyNameList.Count == 0)
                    {
                        // 没有指定属性的情况下全部属性都要转换
                        _DataTable.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    else
                    {
                        if (propertyNameList.Contains(pi.Name))
                        {
                            _DataTable.Columns.Add(pi.Name, pi.PropertyType);
                        }
                    }
                }
                for (int i = 0; i < p_List.Count; i++)//添加内容
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in propertys)
                    {
                        if (propertyNameList.Count == 0)
                        {
                            object obj = pi.GetValue(p_List[i], null);
                            tempList.Add(obj);
                        }
                        else
                        {
                            if (propertyNameList.Contains(pi.Name))
                            {
                                object obj = pi.GetValue(p_List[i], null);
                                tempList.Add(obj);
                            }
                        }
                    }
                    object[] array = tempList.ToArray();
                    _DataTable.LoadDataRow(array, true);
                }
            }
            result.Tables.Add(_DataTable);
            return(result);
        }
Beispiel #28
0
 private System.Data.DataTable ConvertListToDataTable <T>(System.Collections.Generic.IList <T> list, params string[] propertyName)
 {
     System.Collections.Generic.List <string> list2 = new System.Collections.Generic.List <string>();
     if (propertyName != null)
     {
         list2.AddRange(propertyName);
     }
     System.Data.DataTable dataTable = new System.Data.DataTable();
     if (list.Count > 0)
     {
         T t = list[0];
         System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties();
         System.Reflection.PropertyInfo[] array      = properties;
         for (int i = 0; i < array.Length; i++)
         {
             System.Reflection.PropertyInfo propertyInfo = array[i];
             if (list2.Count == 0)
             {
                 dataTable.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
             }
             else
             {
                 if (list2.Contains(propertyInfo.Name))
                 {
                     dataTable.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
                 }
             }
         }
         for (int j = 0; j < list.Count; j++)
         {
             System.Collections.ArrayList     arrayList = new System.Collections.ArrayList();
             System.Reflection.PropertyInfo[] array2    = properties;
             for (int k = 0; k < array2.Length; k++)
             {
                 System.Reflection.PropertyInfo propertyInfo2 = array2[k];
                 if (list2.Count == 0)
                 {
                     object value = propertyInfo2.GetValue(list[j], null);
                     arrayList.Add(value);
                 }
                 else
                 {
                     if (list2.Contains(propertyInfo2.Name))
                     {
                         object value2 = propertyInfo2.GetValue(list[j], null);
                         arrayList.Add(value2);
                     }
                 }
             }
             object[] values = arrayList.ToArray();
             dataTable.LoadDataRow(values, true);
         }
     }
     return(dataTable);
 }
Beispiel #29
0
        public void Build_TwoRows_NumericValuesNonRounded()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");
            var dataSet = new DataSet();
            var dataTable = new DataTable() { TableName = "MyTable" };
            dataTable.Columns.Add(new DataColumn("Id"));
            var numericDataColumn = new DataColumn("Numeric value");
            numericDataColumn.ExtendedProperties.Add("NBi::Type", ColumnType.Numeric);
            dataTable.Columns.Add(numericDataColumn);
            dataTable.Columns.Add(new DataColumn("Boolean value"));
            dataTable.LoadDataRow(new object[] { "Alpha", 10.752, true }, false);
            dataTable.LoadDataRow(new object[] { "Beta", 20.8445585, false }, false);

            var msg = new TableHelper();
            var value = msg.Build(dataTable.Rows.Cast<DataRow>()).ToMarkdown();
            var lines = value.Replace("\n", string.Empty).Split('\r');

            Assert.That(value, Is.StringContaining("10.752 "));
            Assert.That(value, Is.StringContaining("20.8445585"));
        }
Beispiel #30
0
        public void Build_TwoRows_ColumnDelimitersAlligned()
        {
            var dataSet = new DataSet();
            var dataTable = new DataTable() { TableName = "MyTable" };
            dataTable.Columns.Add(new DataColumn("Id"));
            dataTable.Columns.Add(new DataColumn("Numeric value"));
            dataTable.Columns.Add(new DataColumn("Boolean value"));
            dataTable.LoadDataRow(new object[] { "Alpha", 10, true }, false);
            dataTable.LoadDataRow(new object[] { "Beta", 20, false }, false);

            var msg = new TableHelper();
            var value = msg.Build(dataTable.Rows.Cast<DataRow>()).ToMarkdown();
            var lines = value.Replace("\n", string.Empty).Split('\r');

            int pos = 0;
            while ((pos = lines[0].IndexOf('|', pos + 1)) > 0)
            {
                foreach (var line in lines.TakeWhile(l => l.Length>0))
                    Assert.That(line[pos], Is.EqualTo('|'), "The line '{0}' was expecting to have a '|' at position {1} but it was a '{2}'", new object[] {line, pos, line[pos]});
            }
        }
Beispiel #31
0
 private DataTable GetTable()
 {
     var dt = new DataTable();
     var result = DataSource.Matcheds.Select(n => new
     {
         Code = n.Item.Code,
         Name = n.Item.Name,
         Province = n.Item.Province,
         City = n.Item.City,
         District = n.Item.District,
         Industry = n.Item.Type,
         IndustryCode = n.Item.TypeCode,
         //Words = n.Item.Words,
         _Id = n.MatchedInstitutionModel?.Id.ToString(),
         _Name = n.MatchedInstitutionModel?.Name,
         _Province = n.MatchedInstitutionModel?.Province,
         _City = n.MatchedInstitutionModel?.City,
         _District = n.MatchedInstitutionModel?.District,
         _Industry = n.MatchedInstitutionModel?.Type,
         _IndustryCode = n.MatchedInstitutionModel?.TypeCode,
         //_Words = n.MatchedInstitutionModel?.Words,
         Weight = n.MatchedInstitutionModel?.PercentStr,
         InsId = n.MatchedInstitutionModel?.Code
     }).ToList();
     if (result.Any())
     {
         //通过反射获取list中的字段
         var p = result[0].GetType().GetProperties();
         foreach (System.Reflection.PropertyInfo pi in p)
         {
             //Type.GetType(pi.PropertyType.ToString()
             dt.Columns.Add(pi.Name, typeof (String));
         }
         foreach (var t in result)
         {
             IList tempList = new ArrayList();
             //将IList中的一条记录写入ArrayList
             foreach (System.Reflection.PropertyInfo pi in p)
             {
                 var oo = pi.GetValue(t, null);
                 tempList.Add(oo);
             }
             var itm = new object[p.Length];
             for (var j = 0; j < tempList.Count; j++)
             {
                 itm.SetValue(tempList[j], j);
             }
             dt.LoadDataRow(itm, true);
         }
     }
     return dt;
 }
Beispiel #32
0
        private System.Data.DataTable GenerateDataTable <T>(int rows)
        {
            var datatable = new System.Data.DataTable(typeof(T).Name);

            typeof(T).GetProperties().ToList().ForEach(
                x => datatable.Columns.Add(x.Name.Remove(0, 3)));
            Builder <T> .CreateListOfSize(rows).Build()
            .ToList().ForEach(
                x => datatable.LoadDataRow(x.GetType().GetProperties().Select(
                                               y => y.GetValue(x, null)).ToArray(), true));

            return(datatable);
        }
Beispiel #33
0
        public void Build_TwoRows_4Lines()
        {
            var dataSet = new DataSet();
            var dataTable = new DataTable() { TableName = "MyTable" };
            dataTable.Columns.Add(new DataColumn("Id"));
            dataTable.Columns.Add(new DataColumn("Numeric value"));
            dataTable.Columns.Add(new DataColumn("Boolean value"));
            dataTable.LoadDataRow(new object[] { "Alpha", 10, true }, false);
            dataTable.LoadDataRow(new object[] { "Beta", 20, false }, false);

            var msg = new TableHelper();
            var value = msg.Build(dataTable.Rows.Cast<DataRow>()).ToMarkdown();

            Assert.That(value.Count<char>(c => c == '\n'), Is.EqualTo(4));

            var secondLineIndex = value.IndexOf('\n');
            var thirdLineIndex = value.IndexOf('\n', secondLineIndex + 1);
            var secondLine = value.Substring(secondLineIndex+1, thirdLineIndex-secondLineIndex-2);
            Assert.That(secondLine.Distinct<char>().Count(), Is.EqualTo(3));
            Assert.That(secondLine.Distinct<char>(), Has.Member(' '));
            Assert.That(secondLine.Distinct<char>(), Has.Member('-'));
            Assert.That(secondLine.Distinct<char>(), Has.Member('|'));
        }
        public static System.Data.DataTable consulta(System.Data.DataTable profesor, System.Data.DataTable alumno)
        {
            //Result table
            System.Data.DataTable table = new System.Data.DataTable("Union");

            //Build new columns

            DataColumn[] newcolumns = new DataColumn[profesor.Columns.Count];

            for (int i = 0; i < profesor.Columns.Count; i++)

            {
                newcolumns[i] = new DataColumn(profesor.Columns[i].ColumnName, profesor.Columns[i].DataType);
            }

            //add new columns to result table

            table.Columns.AddRange(newcolumns);

            table.BeginLoadData();

            //Load data from first table

            foreach (DataRow row in profesor.Rows)
            {
                table.LoadDataRow(row.ItemArray, true);
            }

            //Load data from second table
            foreach (DataRow row in alumno.Rows)
            {
                table.LoadDataRow(row.ItemArray, true);
            }
            table.EndLoadData();

            return(table);
        }
        public static System.Data.DataTable consulta(System.Data.DataTable profesor,System.Data.DataTable alumno)
        {
            //Result table
            System.Data.DataTable table = new System.Data.DataTable("Union");

            //Build new columns

            DataColumn[] newcolumns = new DataColumn[profesor.Columns.Count];

            for (int i = 0; i < profesor.Columns.Count; i++)

            {
                newcolumns[i] = new DataColumn(profesor.Columns[i].ColumnName, profesor.Columns[i].DataType);
            }

            //add new columns to result table

            table.Columns.AddRange(newcolumns);

            table.BeginLoadData();

            //Load data from first table

            foreach (DataRow row in profesor.Rows)
            {
                table.LoadDataRow(row.ItemArray, true);
            }

            //Load data from second table
            foreach (DataRow row in alumno.Rows)
            {
                table.LoadDataRow(row.ItemArray, true);
            }
            table.EndLoadData();

            return table;
        }
        protected override void RetrieveData(IGenerationContext context)
        {
            DataTable table = new DataTable();
            table.Columns.Add("Value");

            Random rnd = new Random();

            for (int i = 0; i < 100; i++)
            {
                table.LoadDataRow(new object[] { rnd.Next() }, true);
            }

            this.CurrentData = new DataSet();
            this.CurrentData.Tables.Add(table);
        }
        public void Execute()
        {
            var table = new DataTable("SortSampleTable");

            table.Columns.Add("Col1", typeof(string));
            table.Columns.Add("Col2", typeof(string));

            table.LoadDataRow(new object[] {"1", "1"}, true);
            table.LoadDataRow(new object[] {"1", "3"}, true);
            table.LoadDataRow(new object[] {"1", "4"}, true);
            table.LoadDataRow(new object[] {"1", "2"}, true);
            table.LoadDataRow(new object[] {"2", "1"}, true);
            table.LoadDataRow(new object[] {"2", "3"}, true);
            table.LoadDataRow(new object[] {"2", "5"}, true);
            table.LoadDataRow(new object[] {"2", "4"}, true);
            table.LoadDataRow(new object[] {"2", "2"}, true);

            Output.WriteLine("===================================================");
            foreach (DataRow row in table.Rows)
            {
                DumpRow(row);
            }
            Output.WriteLine("===================================================");

            Output.WriteLine("===================================================");
            table.DefaultView.Sort = "Col1 DESC";
            foreach (DataRowView row in table.DefaultView)
            {
                DumpRow(row);
            }
            Output.WriteLine("===================================================");

            Output.WriteLine("===================================================");
            table.DefaultView.Sort = "Col1 ASC";
            foreach (DataRowView row in table.DefaultView)
            {
                DumpRow(row);
            }
            Output.WriteLine("===================================================");
        }
        public DataTable Data(InputColumnHeaders inputColumnHeaders)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Row");
            dt.Columns.Add(inputColumnHeaders.Level1);
            dt.Columns.Add(inputColumnHeaders.Level2);
            dt.Columns.Add(inputColumnHeaders.Level3);

            foreach (KeyValuePair<int, string[]> line in lines2)
            {
                object[] values = {line.Key, line.Value[0], line.Value[1], line.Value[2]};
                dt.LoadDataRow(values, true);
            }

            return dt;
        }
Beispiel #39
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.AreEqual (4, dt.Rows.Count, "#1 has not added a new row");
		}
Beispiel #40
0
        public void Execute()
        {
            var table = new DataTable();

            table.Columns.Add("Val", typeof(int));

            for (var i = 0; i < 10; i++)
            {
                table.LoadDataRow(new object[] {i}, true);
            }

            //
            // Selectメソッドで行を抽出.
            //
            var selectedRows = table.Select("(Val % 2) = 0", "Val");
            selectedRows.ToList().ForEach(row => { Output.WriteLine(row["Val"]); });
        }
Beispiel #41
0
    /// <summary>
    /// 使用指定范围内的行异步填充 DataTable 并返回。
    /// </summary>
    /// <param name="dataReader">用来读取数据的 DataReader</param>
    /// <param name="startRecord">要填充的起始记录位置</param>
    /// <param name="maxRecords">最多填充的记录条数</param>
    /// <returns>填充好的 DataTable</returns>
    public async Task<DataTable> FillDataTableAsync( DbDataReader dataReader, int startRecord, int maxRecords )
    {

      var dataTable = new DataTable();

      base.FillSchema( dataTable, SchemaType.Source, dataReader );

      var array = new object[dataReader.FieldCount];

      while ( await dataReader.ReadAsync() )
      {
        dataReader.GetValues( array );
        dataTable.LoadDataRow( array, true );
      }

      return dataTable;
    }
Beispiel #42
0
        public static DataTable Distinct(DataTable Table, DataColumn[] Columns)
        {
            //Empty table
            DataTable table = new DataTable("Distinct");

            //Sort variable
            string sort = string.Empty;

            //Add Columns & Build Sort expression
            for(int i = 0; i < Columns.Length; i++)
            {
                table.Columns.Add(Columns[i].ColumnName,Columns[i].DataType);
                sort += Columns[i].ColumnName + ",";
            }

            //Select all rows and sort
            DataRow[] sortedrows = Table.Select(string.Empty,sort.Substring(0,sort.Length-1));

            object[] currentrow = null;
            object[] previousrow = null;

            table.BeginLoadData();
            foreach(DataRow row in sortedrows)
            {
                //Current row
                currentrow = new object[Columns.Length];
                for(int i = 0; i < Columns.Length; i++)
                {
                    currentrow[i] = row[Columns[i].ColumnName];
                }

                //Match Current row to previous row
                if(!RowEqual(previousrow, currentrow))
                    table.LoadDataRow(currentrow,true);

                //Previous row
                previousrow = new object[Columns.Length];
                for(int i = 0; i < Columns.Length; i++)
                {
                    previousrow[i] = row[Columns[i].ColumnName];
                }
            }

            table.EndLoadData();
            return table;
        }
Beispiel #43
0
        public void Execute()
        {
            var table = new DataTable();

            table.Columns.Add("Val", typeof(decimal));

            for (var i = 0; i < 10; i++)
            {
                table.LoadDataRow(new object[] {i*0.1}, true);
            }

            //
            // 列は[]付きでも無しでも構わないが、付けておいた方が無難.
            //
            var result = table.Compute("SUM([Val])", "[Val] >= 0.5");
            Output.WriteLine("{0}:{1}", result, result.GetType().FullName);
        }
        private System.Data.DataTable ProcessObjects(object[,] valueArray)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            try
            {
                #region Get the COLUMN names

                for (int k = 1; k <= valueArray.GetLength(1); k++)
                {
                    dt.Columns.Add((string)valueArray[1, k]);
                }
                #endregion

                #region Load Excel SHEET DATA into data table

                object[] singleDValue = new object[valueArray.GetLength(1)];

                for (int i = 2; i <= valueArray.GetLength(0); i++)
                {
                    for (int j = 0; j < valueArray.GetLength(1); j++)
                    {
                        if (valueArray[i, j + 1] != null)
                        {
                            singleDValue[j] = valueArray[i, j + 1].ToString();
                        }
                        else
                        {
                            singleDValue[j] = valueArray[i, j + 1];
                        }
                    }
                    dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
                }
                #endregion
            }
            catch
            {
                throw;
            }
            return(dt);
        }
Beispiel #45
0
        public static DataTable ToDataTable <T>(IEnumerable <T> collection)
        {
            var props = typeof(T).GetProperties();
            var dt    = new System.Data.DataTable();

            dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return(dt);
        }
Beispiel #46
0
        public static System.Data.DataTable DGVToTable(ref System.Windows.Forms.DataGridView dgv)
        {
            System.Data.DataTable table = new System.Data.DataTable();

            foreach (DataGridViewColumn col in dgv.Columns)
            {
                table.Columns.Add(col.HeaderText, typeof(object), String.Empty);
            }

            System.Collections.ArrayList list = new System.Collections.ArrayList();

            foreach (DataGridViewRow row in dgv.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    list.Add(cell.Value);
                }
                table.LoadDataRow(list.ToArray(), true);
                list.Clear();
            }

            return(table);
        }
Beispiel #47
0
    protected void fileUploadComplete(object sender, AsyncFileUploadEventArgs e)
    {
        string folderPath = ConfigurationManager.AppSettings["folderPath"];
        Random rndm       = new Random();
        string filePath   = Server.MapPath(folderPath) + "\\" + rndm.Next() + e.FileName.ToString();

        fileUpload1.SaveAs(filePath);

        var buf = new byte[fileUpload1.FileContent.Length];

        fileUpload1.FileContent.Read(buf, 0, (int)fileUpload1.FileContent.Length);
        System.Data.DataTable dt = new System.Data.DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Grade");
        dt.Columns.Add("Rank");


        object[] aa = buf.Cast <object>().ToArray();

        dt.LoadDataRow(aa, true);

        ImportDataToGrid(filePath);
    }
Beispiel #48
0
    private System.Data.DataTable ProcessObjects(object[,] valueArray)
    {
        System.Data.DataTable dt = new System.Data.DataTable();

        #region Get the COLUMN names

        for (int k = 1; k <= valueArray.GetLength(1); k++)
        {
            dt.Columns.Add((string)valueArray[1, k]);  //add columns to the data table.
        }

        #endregion Get the COLUMN names

        #region Load Excel SHEET DATA into data table

        object[] singleDValue = new object[valueArray.GetLength(1)];
        //value array first row contains column names. so loop starts from 2 instead of 1
        for (int i = 2; i <= valueArray.GetLength(0); i++)
        {
            for (int j = 0; j < valueArray.GetLength(1); j++)
            {
                if (valueArray[i, j + 1] != null)
                {
                    singleDValue[j] = valueArray[i, j + 1].ToString();
                }
                else
                {
                    singleDValue[j] = valueArray[i, j + 1];
                }
            }
            dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
        }

        #endregion Load Excel SHEET DATA into data table

        return(dt);
    }
Beispiel #49
0
        public DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
        {
            //Create Empty Table
            DataTable ResultDataTable = new DataTable("ResultDataTable");

            //use a Dataset to make use of a DataRelation object
            using (DataSet ds = new DataSet())
            {
                //Add tables
                ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });

                //Get Columns for DataRelation
                DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
                for (int i = 0; i < firstColumns.Length; i++)
                {
                    firstColumns[i] = ds.Tables[0].Columns[i];
                }

                DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
                for (int i = 0; i < secondColumns.Length; i++)
                {
                    secondColumns[i] = ds.Tables[1].Columns[i];
                }

                //Create DataRelation
                DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
                ds.Relations.Add(r1);

                DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
                ds.Relations.Add(r2);

                //Create columns for return table
                for (int i = 0; i < FirstDataTable.Columns.Count; i++)
                {
                    ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);
                }

                //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.
                ResultDataTable.BeginLoadData();
                foreach (DataRow parentrow in ds.Tables[0].Rows)
                {
                    DataRow[] childrows = parentrow.GetChildRows(r1);
                    if (childrows == null || childrows.Length == 0)
                    {
                        ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
                    }
                }

                //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.
                foreach (DataRow parentrow in ds.Tables[1].Rows)
                {
                    DataRow[] childrows = parentrow.GetChildRows(r2);
                    if (childrows == null || childrows.Length == 0)
                    {
                        ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
                    }
                }
                ResultDataTable.EndLoadData();
            }

            return(ResultDataTable);
        }
Beispiel #50
0
        /// <summary>
        ///     Selects all rows from both tables as long as there is a match between the columns in both tables.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="child">The child.</param>
        /// <param name="parentDataColumns">The parent data columns.</param>
        /// <param name="childDataColumns">The child data columns.</param>
        /// <returns>
        ///     Returns a <see cref="DataTable" /> representing the joined table.
        /// </returns>
        /// <remarks>
        ///     This JOIN method is equivalent to the TSQL INNER JOIN expression using equality.
        /// </remarks>
        public static DataTable Join(this DataTable source, DataTable child, DataColumn[] parentDataColumns, DataColumn[] childDataColumns)
        {
            DataTable table = new DataTable(source.TableName + "_" + child.TableName);

            using (DataSet ds = new DataSet())
            {
                ds.Tables.AddRange(new[] { source.Copy(), child.Copy() });

                DataColumn[] parentColumns = new DataColumn[parentDataColumns.Length];
                for (int i = 0; i < parentColumns.Length; i++)
                {
                    parentColumns[i] = ds.Tables[0].Columns[parentDataColumns[i].ColumnName];
                }

                DataColumn[] childColumns = new DataColumn[childDataColumns.Length];
                for (int i = 0; i < childColumns.Length; i++)
                {
                    childColumns[i] = ds.Tables[1].Columns[childDataColumns[i].ColumnName];
                }

                DataRelation r = new DataRelation(string.Empty, parentColumns, childColumns, false);
                ds.Relations.Add(r);

                for (int i = 0; i < source.Columns.Count; i++)
                {
                    table.Columns.Add(source.Columns[i].ColumnName, source.Columns[i].DataType);
                }

                var dataColumns = new List <DataColumn>();
                for (int i = 0; i < child.Columns.Count; i++)
                {
                    if (!table.Columns.Contains(child.Columns[i].ColumnName))
                    {
                        table.Columns.Add(child.Columns[i].ColumnName, child.Columns[i].DataType);
                    }
                    else
                    {
                        dataColumns.Add(child.Columns[i]);
                    }
                }

                table.BeginLoadData();

                foreach (DataRow parentRow in ds.Tables[0].Rows)
                {
                    var parent    = parentRow.ItemArray;
                    var childRows = parentRow.GetChildRows(r);
                    if (childRows.Any())
                    {
                        foreach (DataRow childRow in childRows)
                        {
                            var children = childRow.ItemArray.Where((value, i) => !dataColumns.Select(o => o.Ordinal).Contains(i)).ToArray();
                            var join     = new object[parent.Length + children.Length];

                            Array.Copy(parent, 0, join, 0, parent.Length);
                            Array.Copy(children, 0, join, parent.Length, children.Length);

                            table.LoadDataRow(join, true);
                        }
                    }
                }

                table.EndLoadData();
            }

            return(table);
        }
Beispiel #51
0
        public void TransDataGridViewToDictionaryTest()
        {
            var datatable = new System.Data.DataTable(typeof(HangDTO).Name);

            datatable.Columns.Add("Mã Hàng");
            datatable.Columns.Add("Tên Hàng");
            datatable.Columns.Add("Đơn Giá");
            datatable.Columns.Add("Số Lượng");
            datatable.Columns.Add("Ghi Chú");
            Builder <HangDTO> .CreateListOfSize(10).Build()
            .ToList().ForEach(
                x => datatable.LoadDataRow(x.GetType().GetProperties().Select(
                                               y => y.GetValue(x, null)).ToArray(), true));

            //return datatable;
            System.Windows.Forms.DataGridView dataGridView = new System.Windows.Forms.DataGridView();
            datatable.AcceptChanges();

            dataGridView.DataSource = datatable;

            var listHang = Builder <HangDTO> .CreateListOfSize(10).Build();

            List <HangDTO> list = new List <HangDTO>(listHang);


            var data = GenerateDataTable <HangDTO>(10);

            var datatable2 = new System.Data.DataTable(typeof(HangDTO).Name);

            var data2 = GenerateDataTable <HangDTO>(12);

            //var mockIMapper = new Mock<IMapper>();
            //mockIMapper.Setup(x => x.Map<List<DataGridViewRow>, List<HangDTO>>(It.IsNotNull<List<DataGridViewRow>>())).Returns(list);// dataGridView.Rows.OfType<DataGridViewRow>().ToList())).Returns(list);

            System.Windows.Forms.DataGridView dataGridView1 = new System.Windows.Forms.DataGridView
            {
                ColumnCount = 5
            };
            dataGridView1.Columns[0].Name = "Mã Hàng";
            dataGridView1.Columns[1].Name = "Tên Hàng";
            dataGridView1.Columns[2].Name = "Đơn Giá";
            dataGridView1.Columns[3].Name = "Ghi Chú";
            dataGridView1.Columns[4].Name = "Số Lượng";


            string[] row = new string[] { "1", "Product 1", "1000", "", "50" };
            dataGridView1.Rows.Add(row);
            row = new string[] { "2", "Product 2", "2000", "", "20" };
            dataGridView1.Rows.Add(row);

            mockIDataProvider.Setup(x => x.ExecuteQuery(It.IsNotNull <string>(), null)).Returns(data);
            mockIDataProvider.Setup(x => x.ExecuteNonQuery(It.IsNotNull <string>(), It.IsNotNull <object[]>())).Returns(1);
            mockIDataProvider.Setup(x => x.ExecuteScalar(It.IsNotNull <string>(), It.IsNotNull <object[]>())).Returns(10);
            var result1 = quanLyThongTinBUS.TransDataGridViewToDictionary(dataGridView1, true);//,mockIMapper.Object);

            dataGridView.DataSource = data;
            var result2 = quanLyThongTinBUS.TransDataGridViewToDictionary(dataGridView, false);//,mockIMapper.Object);

            dataGridView.DataSource = data2;
            var result  = quanLyThongTinBUS.NhapXuatHang(dataGridView, true, "jh");
            var result3 = quanLyThongTinBUS.TransDataGridViewToDictionary(dataGridView, false);

            dataGridView.DataSource = datatable2;
            var result4 = quanLyThongTinBUS.TransDataGridViewToDictionary(dataGridView, true);


            // Assert.IsNotNull(result);
            Assert.IsNotEmpty(result1.Item2);
            Assert.IsEmpty(result1.Item1);
            Assert.IsNotEmpty(result2.Item1);
            Assert.IsEmpty(result2.Item2);
            Assert.IsNotEmpty(result3.Item1);
            Assert.IsNotEmpty(result3.Item2);
            Assert.IsEmpty(result4.Item1);
            Assert.IsEmpty(result4.Item2);
            mockIDataProvider.VerifyAll();
        }
Beispiel #52
0
        /// <summary>
        /// The Product Method is the equivalent of the CROSS JOIN expression in TSQL.
        /// </summary>
        /// <param name="First"></param>
        /// <param name="Second"></param>
        /// <returns></returns>
        /// <remarks>Create new empty table<br>
        /// Add columns from First table to empty table.<br>
        /// Add columns from Secondtable to empty table. Rename if necessary<br>
        /// Loop through First table and for each row loop through Second table and add rows via array manipulation.<br>
        /// Return Table.</remarks>
        public static DataTable Product(DataTable First, DataTable Second)

        {
            DataTable table = new DataTable("Product");

            //Add Columns from First

            for (int i = 0; i < First.Columns.Count; i++)

            {
                table.Columns.Add(new DataColumn(First.Columns[i].ColumnName, First.Columns[i].DataType));
            }



            //Add Columns from Second

            for (int i = 0; i < Second.Columns.Count; i++)

            {
                //Beware Duplicates

                if (!table.Columns.Contains(Second.Columns[i].ColumnName))
                {
                    table.Columns.Add(new DataColumn(Second.Columns[i].ColumnName, Second.Columns[i].DataType));
                }

                else
                {
                    table.Columns.Add(new DataColumn(Second.Columns[i].ColumnName + "_Second", Second.Columns[i].DataType));
                }
            }



            table.BeginLoadData();

            foreach (DataRow parentrow in First.Rows)

            {
                object[] firstarray = parentrow.ItemArray;

                foreach (DataRow childrow in Second.Rows)

                {
                    object[] secondarray = childrow.ItemArray;

                    object[] productarray = new object[firstarray.Length + secondarray.Length];

                    Array.Copy(firstarray, 0, productarray, 0, firstarray.Length);

                    Array.Copy(secondarray, 0, productarray, firstarray.Length, secondarray.Length);



                    table.LoadDataRow(productarray, true);
                }
            }

            table.EndLoadData();



            return(table);
        }
Beispiel #53
0
        /// <summary>
        /// It is also refered to as MINUS and is simply all the rows that are in the First table but not the Second.
        /// </summary>
        /// <param name="First"></param>
        /// <param name="Second"></param>
        /// <returns></returns>
        /// <remarks>
        /// Create new empty table<br>
        /// Create a DataSet and add tables.<br>
        /// Get a reference to all columns in both tables<br>
        /// Create a DataRelation<br>
        /// Using the DataRelation add rows with no child rows.<br>
        /// Return table<br>
        /// </remarks>
        public static DataTable Difference(DataTable First, DataTable Second)

        {
            //Create Empty Table

            DataTable table = new DataTable("Difference");



            //Must use a Dataset to make use of a DataRelation object

            using (DataSet ds = new DataSet())

            {
                //Add tables

                ds.Tables.AddRange(new DataTable[] { First.Copy(), Second.Copy() });

                //Get Columns for DataRelation

                DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

                for (int i = 0; i < firstcolumns.Length; i++)

                {
                    firstcolumns[i] = ds.Tables[0].Columns[i];
                }



                DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];

                for (int i = 0; i < secondcolumns.Length; i++)

                {
                    secondcolumns[i] = ds.Tables[1].Columns[i];
                }

                //Create DataRelation

                DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

                ds.Relations.Add(r);



                //Create columns for return table

                for (int i = 0; i < First.Columns.Count; i++)

                {
                    table.Columns.Add(First.Columns[i].ColumnName, First.Columns[i].DataType);
                }



                //If First Row not in Second, Add to return table.

                table.BeginLoadData();

                foreach (DataRow parentrow in ds.Tables[0].Rows)

                {
                    DataRow[] childrows = parentrow.GetChildRows(r);

                    if (childrows == null || childrows.Length == 0)
                    {
                        table.LoadDataRow(parentrow.ItemArray, true);
                    }
                }

                table.EndLoadData();
            }



            return(table);
        }
Beispiel #54
0
        //FJC = First Join Column
        //SJC = Second Join Column
        /// <summary>
        /// INNER JOIN
        /// </summary>
        /// <param name="First"></param>
        /// <param name="Second"></param>
        /// <param name="FJC"></param>
        /// <param name="SJC"></param>
        /// <returns></returns>
        /// <remarks>
        /// This JOIN method is equivalent to the TSQL INNER JOIN expression using equality.<br>
        /// This method returns all columns from both tables.<br>
        /// Once again, column name collision is avoided by appending "_Second" to the columns affected.<br>
        /// There are a total of 3 signatures for this method.<br>
        /// In summary the code works as follows:<br>
        /// Create new empty table<br>
        /// Create a DataSet and add tables.<br>
        /// Get a reference to Join columns<br>
        /// Create a DataRelation<br>
        /// Construct JOIN table columns<br>
        /// Using the DataRelation add rows with matching related rows using array manipulation<br>
        /// Return table<br>
        /// </remarks>
        public static DataTable Join(DataTable First, DataTable Second, DataColumn[] FJC, DataColumn[] SJC)

        {
            //Create Empty Table

            DataTable table = new DataTable("Join");



            // Use a DataSet to leverage DataRelation

            using (DataSet ds = new DataSet())

            {
                //Add Copy of Tables

                ds.Tables.AddRange(new DataTable[] { First.Copy(), Second.Copy() });



                //Identify Joining Columns from First

                DataColumn[] parentcolumns = new DataColumn[FJC.Length];

                for (int i = 0; i < parentcolumns.Length; i++)

                {
                    parentcolumns[i] = ds.Tables[0].Columns[FJC[i].ColumnName];
                }

                //Identify Joining Columns from Second

                DataColumn[] childcolumns = new DataColumn[SJC.Length];

                for (int i = 0; i < childcolumns.Length; i++)

                {
                    childcolumns[i] = ds.Tables[1].Columns[SJC[i].ColumnName];
                }



                //Create DataRelation

                DataRelation r = new DataRelation(string.Empty, parentcolumns, childcolumns, false);

                ds.Relations.Add(r);



                //Create Columns for JOIN table

                for (int i = 0; i < First.Columns.Count; i++)

                {
                    table.Columns.Add(First.Columns[i].ColumnName, First.Columns[i].DataType);
                }

                for (int i = 0; i < Second.Columns.Count; i++)

                {
                    //Beware Duplicates

                    if (!table.Columns.Contains(Second.Columns[i].ColumnName))
                    {
                        table.Columns.Add(Second.Columns[i].ColumnName, Second.Columns[i].DataType);
                    }

                    else
                    {
                        table.Columns.Add(Second.Columns[i].ColumnName + "_Second", Second.Columns[i].DataType);
                    }
                }



                //Loop through First table

                table.BeginLoadData();

                foreach (DataRow firstrow in ds.Tables[0].Rows)

                {
                    //Get "joined" rows

                    DataRow[] childrows = firstrow.GetChildRows(r);

                    if (childrows != null && childrows.Length > 0)

                    {
                        object[] parentarray = firstrow.ItemArray;

                        foreach (DataRow secondrow in childrows)

                        {
                            object[] secondarray = secondrow.ItemArray;

                            object[] joinarray = new object[parentarray.Length + secondarray.Length];

                            Array.Copy(parentarray, 0, joinarray, 0, parentarray.Length);

                            Array.Copy(secondarray, 0, joinarray, parentarray.Length, secondarray.Length);

                            table.LoadDataRow(joinarray, true);
                        }
                    }
                }

                table.EndLoadData();
            }



            return(table);
        }
Beispiel #55
0
        /// <summary>
        /// Removes the equal rows
        /// </summary>
        /// <param name="Table"></param>
        /// <param name="Columns"></param>
        /// <returns></returns>
        public static DataTable Distinct(DataTable Table, DataColumn[] Columns)

        {
            //Empty table

            DataTable table = new DataTable("Distinct");

            //Sort variable

            string sort = string.Empty;



            //Add Columns & Build Sort expression

            for (int i = 0; i < Columns.Length; i++)

            {
                table.Columns.Add(Columns[i].ColumnName, Columns[i].DataType);

                sort += Columns[i].ColumnName + ",";
            }

            //Select all rows and sort

            DataRow[] sortedrows = Table.Select(string.Empty, sort.Substring(0, sort.Length - 1));



            object[] currentrow = null;

            object[] previousrow = null;



            table.BeginLoadData();

            foreach (DataRow row in sortedrows)

            {
                //Current row

                currentrow = new object[Columns.Length];

                for (int i = 0; i < Columns.Length; i++)

                {
                    currentrow[i] = row[Columns[i].ColumnName];
                }



                //Match Current row to previous row

                if (!SQLOps.RowEqual(previousrow, currentrow))
                {
                    table.LoadDataRow(currentrow, true);
                }



                //Previous row

                previousrow = new object[Columns.Length];

                for (int i = 0; i < Columns.Length; i++)

                {
                    previousrow[i] = row[Columns[i].ColumnName];
                }
            }

            table.EndLoadData();

            return(table);
        }
        internal static DataTable ReadFile(string path, int numberColumn)
        {
            char[] tabs = { '\t' };         // tab ngang
            char[] quotes = { '\"' };       // dấu nháy kép "

            DataTable table = new DataTable("dataFromFile");


            for (int i = 0; i < numberColumn; i++)
            {
                table.Columns.Add(new DataColumn("col" + i, typeof(string)));
            }

            using (StreamReader sr = new StreamReader(path))
            {
                table.BeginLoadData();
                string line;
                //int rowsCount = 0;

                string firstLine = sr.ReadLine();
                // string otherLine = sr.ReadToEnd();

                //  string[] firstLineData = firstLine.Split(new[] { "\"", "\t" }, StringSplitOptions.RemoveEmptyEntries);

                string[] firstLineData = (
                    from s in firstLine.Split(tabs)
                    select s.Trim(quotes)).ToArray();

                if (firstLineData.Length == numberColumn)
                {
                    table.LoadDataRow(firstLineData, true);
                    //rowsCount++;
                }
                else
                {
                    foreach (string item in firstLineData)
                    {
                        if (item != String.Empty)
                        {
                            table.Rows.Add();
                            table.Rows[0][0] = item;
                            //  rowsCount++;
                            break;
                        }
                    }
                }

                while (true)
                {
                    line = sr.ReadLine();
                    if (line == null) break;

                    string[] array = (
                        from s in line.Split(tabs)
                        select s.Trim(quotes)).ToArray();

                    if (array.Length == numberColumn)
                    {
                        table.LoadDataRow(array, true);
                    }
                }

            }

            table.EndLoadData();
            return table;
        }