-1

I have DataTable and I need to add row with default values and save it into database.

BONUS: Would be awesome to auto increment key column.

How can I achieve that?

Litisqe Kumar
  • 2,512
  • 4
  • 26
  • 40
Farukh
  • 2,173
  • 2
  • 23
  • 38
  • Look at this doc from MSDN: https://msdn.microsoft.com/en-us/library/system.data.datacolumn.defaultvalue(v=vs.110).aspx - but you should consider doing this at the database level (if youa re using a database) at least for auto-increment key. – David Tansey Oct 10 '15 at 05:37

2 Answers2

0
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);
}

Variable i will be auto increment key column. Now Insert the DataTable to DataBase.

Daniel
  • 9,491
  • 12
  • 50
  • 66
Litisqe Kumar
  • 2,512
  • 4
  • 26
  • 40
-2

You can add a new row with default values and save it into database like this.

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");
}

Also, if you've set an auto increment key like IDENTITY for MS SQL Server (https://msdn.microsoft.com/en-us/library/ms186775.aspx), this works when the new row is inserted.

jhmt
  • 1,401
  • 1
  • 11
  • 15
  • Could you please show your connectionString(except password, etc...) and name all the columns with its default values? I'd like to figure out why this didn't work in your database. – jhmt Oct 11 '15 at 03:40