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++;
}
}
}
Columns["Col"]. DefaultValue="Name"; To add default value to all rows we have to use the for each loop inside Datatable.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With