DataColumn set a default value

时光毁灭记忆、已成空白 提交于 2021-01-27 07:39:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!