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();
        }
Example #2
0
 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;
 }
Example #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 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;
        }
Example #5
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;

    }
Example #6
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;
		}
Example #7
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);
            }
        }
Example #8
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;
        }
Example #9
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;
        }
Example #10
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;
 }
Example #11
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;
        }
Example #12
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++;
            }
        }
Example #13
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;
        }
Example #14
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);

      });
    }
Example #15
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;
 }
Example #16
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;
 }
Example #17
0
        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;
        }
Example #18
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"));
        }
Example #19
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]});
            }
        }
Example #20
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;
 }
Example #21
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;
        }
        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;
        }
Example #26
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");
		}
Example #27
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;
        }
Example #28
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"]); });
        }
Example #29
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;
    }
Example #30
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);
        }