Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataColumn set a default value

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++;
        }
    }
}
like image 303
user406151 Avatar asked Jan 15 '15 03:01

user406151


People also ask

How to set default value in DataTable?

Columns["Col"]. DefaultValue="Name"; To add default value to all rows we have to use the for each loop inside Datatable.


2 Answers

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

like image 130
DRapp Avatar answered Sep 24 '22 07:09

DRapp


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

like image 23
Edward Eisenhart Avatar answered Sep 24 '22 07:09

Edward Eisenhart