C# DataRow.ItemArray 属性

DataRow.ItemArray 属性
通过一个数组来获取或设置此行的所有值。
命名空间:System.Data

程序集:System.Data(在 system.data.dll 中)

代码示例:

private void CreateRowsWithItemArray()
{
    // Make a DataTable using the function below.
    DataTable dt = MakeTableWithAutoIncrement();
    DataRow relation;
    // Declare the array variable.
    object [] rowArray = new object[2];
    // Create 10 new rows and add to DataRowCollection.
    for(int i = 0; i <10; i++)
    {
        rowArray[0]=null;
        rowArray[1]= "item " + i;
        relation = dt.NewRow();
        relation.ItemArray = rowArray;
        dt.Rows.Add(relation);
    }
    PrintTable(dt);
}
 
private DataTable MakeTableWithAutoIncrement()
{
    // Make a table with one AutoIncrement column.
    DataTable table = new DataTable("table");
    DataColumn idColumn = new DataColumn("id", 
        Type.GetType("System.Int32"));
    idColumn.AutoIncrement = true;
    idColumn.AutoIncrementSeed = 10;
    table.Columns.Add(idColumn);

    DataColumn firstNameColumn = new DataColumn("Item", 
        Type.GetType("System.String"));
    table.Columns.Add(firstNameColumn);
    return table;
}
 
private void PrintTable(DataTable table)
{
    foreach(DataRow row in table.Rows)
    {
        foreach(DataColumn column in table.Columns)
        {
            Console.WriteLine(row[column]);
        }
    }
}
异常:

异常类型 条件

ArgumentException

数组大于表中的列数。

InvalidCastException

数组中的值与其相应的 DataColumn 中的 DataType 不匹配。

ConstraintException

编辑破坏了约束。

ReadOnlyException

编辑试图更改只读列的值。

NoNullAllowedException

编辑试图将空值放在 DataColumn 对象的 AllowDBNull 为 false 的列中。

DeletedRowInaccessibleException

该行已被删除。

DataRow.ItemArray 属性源代码实现:

public object[] ItemArray
{
	get
	{
		int defaultRecord = this.GetDefaultRecord();
		object[] array = new object[this._columns.Count];
		for (int i = 0; i < array.Length; i++)
		{
			DataColumn dataColumn = this._columns[i];
			array[i] = dataColumn[defaultRecord];
		}
		return array;
	}
	set
	{
		if (value == null)
		{
			throw ExceptionBuilder.ArgumentNull("ItemArray");
		}
		if (this._columns.Count < value.Length)
		{
			throw ExceptionBuilder.ValueArrayLength();
		}
		DataColumnChangeEventArgs dataColumnChangeEventArgs = null;
		if (this._table.NeedColumnChangeEvents)
		{
			dataColumnChangeEventArgs = new DataColumnChangeEventArgs(this);
		}
		bool flag = this.BeginEditInternal();
		for (int i = 0; i < value.Length; i++)
		{
			if (value[i] != null)
			{
				DataColumn dataColumn = this._columns[i];
				if (-1L != this.rowID && dataColumn.ReadOnly)
				{
					throw ExceptionBuilder.ReadOnly(dataColumn.ColumnName);
				}
				if (dataColumnChangeEventArgs != null)
				{
					dataColumnChangeEventArgs.InitializeColumnChangeEvent(dataColumn, value[i]);
					this._table.OnColumnChanging(dataColumnChangeEventArgs);
				}
				if (dataColumn.Table != this._table)
				{
					throw ExceptionBuilder.ColumnNotInTheTable(dataColumn.ColumnName, this._table.TableName);
				}
				if (-1L != this.rowID && dataColumn.ReadOnly)
				{
					throw ExceptionBuilder.ReadOnly(dataColumn.ColumnName);
				}
				if (this.tempRecord == -1)
				{
					this.BeginEditInternal();
				}
				object obj = (dataColumnChangeEventArgs != null) ? dataColumnChangeEventArgs.ProposedValue : value[i];
				if (obj == null)
				{
					if (dataColumn.IsValueType)
					{
						throw ExceptionBuilder.CannotSetToNull(dataColumn);
					}
					obj = DBNull.Value;
				}
				try
				{
					int proposedRecordNo = this.GetProposedRecordNo();
					dataColumn[proposedRecordNo] = obj;
				}
				catch (Exception e)
				{
					if (ADP.IsCatchableOrSecurityExceptionType(e) && flag)
					{
						this.CancelEdit();
					}
					throw;
				}
				this.LastChangedColumn = dataColumn;
				if (dataColumnChangeEventArgs != null)
				{
					this._table.OnColumnChanged(dataColumnChangeEventArgs);
				}
			}
		}
		this.EndEdit();
	}
}


### 定期读取Excel (.xls) 文件 为了实现使用 C# 定时器定期读取 `.xls` 文件的功能,可以通过 `System.Timers.Timer` 类设置定时任务,并利用 OleDB 或者第三方库如 ExcelDataReader 来处理 Excel 文件。下面展示一种基于 OleDB 的解决方案。 #### 使用 System.Timers.Timer 和 OleDB 实现定时读取 .xls 文件 ```csharp using System; using System.Data; using System.Data.OleDb; public class ExcelReaderTimer { private Timer _timer; public void StartReading(string filePath, double intervalInSeconds){ // 创建并配置计时器对象 _timer = new Timer(intervalInSeconds * 1000); _timer.Elapsed += (sender, e) => ReadExcelFile(filePath); _timer.AutoReset = true; _timer.Enabled = true; } private void ReadExcelFile(string path){ try{ string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;IMEX=1\";"; using(OleDbConnection connection = new OleDbConnection(connectionString)){ connection.Open(); DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString(); string query = $"SELECT * FROM [{sheetName}]"; using(OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection)){ DataSet dataSet = new DataSet(); adapter.Fill(dataSet); foreach(DataRow row in dataSet.Tables[0].Rows){ Console.WriteLine($"Processing Row: {row.ItemArray[0]}"); } } } }catch(Exception ex){ Console.WriteLine(ex.Message); } } } ``` 此代码片段展示了如何创建一个名为 `ExcelReaderTimer` 的类[^3],该类内部定义了一个私有字段 `_timer` 存储定时器实例。通过 `StartReading()` 方法启动定时器,指定要监控的目标文件路径以及间隔秒数;而在每次触发事件时,则会调用 `ReadExcelFile()` 函数尝试加载最新的 Excel 表格内容到内存中进行处理[^1]。 需要注意的是,在实际项目部署前应当考虑异常情况下的错误恢复机制,比如网络断开重连逻辑、日志记录等功能模块的设计与集成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值