.NET:如何更改DataTable中的值
-
06-07-2019 - |
题
在ADO.NET中,我正在使用 GetSchemaTable 返回结果集的架构表。
DataTable schema = rdr.GetSchemaTable();
gridSchema.DataSource = schema;
gridSchema.DataBind();
不幸的是," ProviderType" 值显示为整数,而不是 OleDbType 它的枚举值:
ProviderType Desired Display Value
============ =====================
129 Char
3 Integer
129 Char
129 Char
3 Integer
3 Integer
129 Char
135 DBTimeStamp
129 Char
129 Char
...
所有这些整数都是 OleDbType 枚举:
public enum OleDbType
{
Empty = 0,
SmallInt = 2,
Integer = 3,
Single = 4,
Double = 5,
Currency = 6,
Date = 7,
BSTR = 8,
IDispatch = 9,
Error = 10,
Boolean = 11,
Variant = 12,
IUnknown = 13,
Decimal = 14,
TinyInt = 16,
UnsignedTinyInt = 17,
UnsignedSmallInt = 18,
UnsignedInt = 19,
BigInt = 20,
UnsignedBigInt = 21,
Filetime = 64,
Guid = 72,
Binary = 128,
Char = 129,
WChar = 130,
Numeric = 131,
DBDate = 133,
DBTime = 134,
DBTimeStamp = 135,
PropVariant = 138,
VarNumeric = 139,
VarChar = 200,
LongVarChar = 201,
VarWChar = 202,
LongVarWChar = 203,
VarBinary = 204,
LongVarBinary = 205,
}
我希望将数据类型显示为人类可读的内容,而不是整数。
我尝试循环遍历架构DataTable并修改DataTable中的值:
DataTable schema = rdr.GetSchemaTable();
//Change providerType column to be readable
foreach (DataRow row in schema.Rows)
{
OleDbType t = (OleDbType)row["ProviderType"];
row["ProviderType"] = t.ToString();
}
gridSchema.DataSource = schema;
gridSchema.DataBind();
但这引发了一个例外:
Column 'ProviderType' is read only.
我甚至看过GridView的 RowDataBound 事件,我想我可以在呈现时更改值:
protected void gridSchema_RowDataBound(object sender, GridViewRowEventArgs e)
{
//todo: magic
//e.Row["ProviderType"]
}
但看起来你不能使用渲染值。
任何人都可以通过 ProviderType 列的价值提出一个很好的方法,以便在我向人类展示时它是人类可读的吗?
更新
我现在正在使用的解决方法是在最后添加一个额外的列:
DataTable schema = rdr.GetSchemaTable();
schema.Columns.Add("OleDbDataType", typeof(String));
schema.Columns.Add("CLRDataType", typeof(String));
foreach (DataRow row in schema.Rows)
{
//Show the actual provider type
OleDbType t = (OleDbType)row["ProviderType"];
row["OleDbDataType"] = t.ToString();
//Show the corresponding CLR type while we're doing a hack
row["CLRDataType"] = row["DataType"].ToString();
}
gridSchema.DataSource = schema;
gridSchema.DataBind();
解决方案
我可能完全不在这里,但你不能只将列的ReadOnly属性设置为false吗?像:
schema.Columns["ProviderType"].ReadOnly = false;
之后,当您尝试将字符串值放入整数列时,可能会出现columntype问题。但这应该让你走向正确的方向。
修改强>
解决columntype问题:
DataTable newTable = schema.Clone();
newTable.Columns["ProviderType"].DataType = typeof(string);
foreach (DataRow dr in schema.Rows)
{
DataRow newRow = newTable.NewRow();
// fill newRow with correct data and newly formatted providertype
newTable.Rows.Add(newRow);
}
其他提示
或者您可以使用数据表中的所有字段创建一个对象,将所有数据传递到您的对象并对其进行修改,或者创建一个只读字段,该字段根据给定的整数返回字符串。
GridView和其他人也接受对象数组作为数据源,因此它是自动的。
不隶属于 StackOverflow