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?
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?
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
.
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.