问题
I am trying to set a default value for a DataColumn. How do you set a default value for DataColumn (column3) for the below code
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] {
new DataColumn("Column1", typeof(String)),
new DataColumn("Column2", typeof(String)),
new DataColumn("Column3", typeof(String)),
});
string csvData = File.ReadAllText(csvPath);
foreach (string row in csvData.Split('\n'))
{
if (!string.IsNullOrEmpty(row))
{
dt.Rows.Add();
int i = 0;
foreach (string cell in row.Split(','))
{
dt.Rows[dt.Rows.Count - 1][i] = cell;
i++;
}
}
}
回答1:
The Columns has a "DefaultValue" property, so you could do
dt.Columns["Column1"].DefaultValue = "testing";
dt.Columns["Column2"].DefaultValue = "blah";
dt.Columns["Column3"].DefaultValue = "";
Then, when you do
DataRow dr = dt.NewRow();
dr.columns 1, 2 and 3 will have respective default values
回答2:
There is a DefaultValue property in the DataColumn class.
dt.Columns["Column3"].DefaultValue = "default";
See http://msdn.microsoft.com/en-us/library/system.data.datacolumn%28v=vs.110%29.aspx
回答3:
This default value we can use when we insert a new DataRow into DataTable.
dt.Columns["Col"].DefaultValue="Name";
To add default value to all rows we have to use the for each loop inside Datatable.
回答4:
You can also do it with the return value from Columns.Add
var col = result.Columns.Add("Column1", typeof(CellObject));
col.DefaultValue = new CellObject { Value = null };
来源:https://stackoverflow.com/questions/27956513/datacolumn-set-a-default-value