遍历行,随时更新值绝对是一种解决方案,而且非常简单:
foreach (DataRow row in table.Rows)
{
if (row.IsNull("foo")) row["foo"] = "-";
if (row.IsNull("bar")) row["bar"] = "-";
row["date"] = ((DateTime)row["date"]).Date;
}
或者,您可以在表中创建新列,使用 expressions 自动生成内容:
table.Columns.Add("foo_dash", typeof(string), "IsNull(foo, '-')");
table.Columns.Add("bar_dash", typeof(string), "IsNull(bar, '-')");
(我不知道 ADO.NET 中的日期函数,所以你必须自己弄清楚最后一个。)
您已将您的帖子标记为 ASP.NET,因此我想假设您要将 DataTable 绑定到一些多记录数据控件(GridView、Repeater 等)是合理的。如果是这种情况,最好在数据绑定期间进行转换:
protected void theGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
var data = e.DataItem as DataRowView;
if (data != null)
{
if (data.Row.IsNull("foo")) e.Row.Cells[0] = "-";
if (data.Row.IsNull("bar")) e.Row.Cells[0] = "-";
}
}
虽然这似乎需要更多代码,但它也为您提供了更大的灵活性。示例:
if (data.Row.IsNull("importantField")) e.Row.CssClass = "error";
在GridView 中,可以在列声明中使用DataFormatString 格式化日期:
<asp:BoundField DataField="data" DataFormatString="{0:d}" />
与Repeater 绑定数据时类似:
<%# Eval("date", "{0:d}") %>