Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将具有默认值的行添加到System.Data.DataTable中_C#_Datatable_System.data - Fatal编程技术网

C# 如何将具有默认值的行添加到System.Data.DataTable中

C# 如何将具有默认值的行添加到System.Data.DataTable中,c#,datatable,system.data,C#,Datatable,System.data,我有数据表,我需要添加带有默认值的行,并将其保存到数据库中 奖励:自动增加键列会很棒 我怎样才能做到这一点 static int i = 1; private void CreateDefault() { DataColumn column = null; DataTable table = new DataTable(); column = new DataColumn(); var Col1 = column; Col1.DataType = Sys

我有
数据表
,我需要添加带有默认值的
,并将其保存到数据库中

奖励:自动增加键列会很棒

我怎样才能做到这一点

static int i = 1;
private void CreateDefault()
{
    DataColumn column = null;
    DataTable table = new DataTable();

    column = new DataColumn();
    var Col1 = column;
    Col1.DataType = System.Type.GetType("System.Int32");
    Col1.DefaultValue = i;
    Col1.Unique = false;
    table.Columns.Add(column);
    i = i + 1;

    column = new DataColumn();
    var Col2 = column;
    Col2.DataType = System.Type.GetType("System.String");
    Col2.DefaultValue = "Your String";
    table.Columns.Add(column);

    DataRow row = null;
    row = table.NewRow();

    table.Rows.Add(row);
}

变量
i
将自动递增键列。现在将
数据表
插入
数据库

您可以添加一个具有默认值的新行,并将其保存到数据库中,如下所示

using (var conn = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand("SELECT * FROM YourTableName", conn);
    SqlDataAdapter da = new SqlDataAdapter() { SelectCommand = cmd };

    // Load records to a DataSet
    DataSet ds = new DataSet();
    da.Fill(ds, "YourTableName");
    var table = ds.Tables["YourTableName"];

    // Add a new row with default value
    table.Rows.Add();

    // Reflect the change to database
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    da.Update(ds, "YourTableName");
}

此外,如果您为MSSQLServer()设置了一个自动增量键,则在插入新行时会起作用。

从MSDN中查看这个DOC:但是,您应该考虑在数据库级(如果您重新使用数据库)这样做,至少是为了自动增量键。请显示连接字符串(除了密码等)。并用其默认值命名所有列?我想弄清楚为什么在你的数据库中这不起作用。