Working With AutoIncrement Property of DataColumn Class in ADO.NET


Introduction

The column's value of a new row can be incremented by the AutoIncrement property of the DataColumn class. At first, set the AutoIncrement property to true. The two other properties used with the AutoIncrement property are AutoIncrementSeed and AutoIncrementStep.

  • AutoIncrementSeed : It is used to set initial value for increment.
  • AutoIncrementStep : It is used to set value to be increment.

Now we use these properties in our application. I am creating a simple application in which I am sending the value from textbox to DataTable's row and showing the value of DataTable into DataDridView. Open Visual Studio 2010 and take a Window Form Application. Write the following code.

using System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;

namespace
parameterclass
{
public partialclass Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnok_Click(object sender,EventArgs e)
{
// Creating new row and assigning value to column
DataRow dr = dtable.NewRow();
dr[1]=textBox1.Text;
dr[2] = int.Parse(textBox2.Text);
dr[3] = textBox3.Text;
// Adding DataRow to DataTable
dtable.Rows.Add(dr);
// Binding DataGridView to DataTable
dataGridView1.DataSource = dtable;
}
DataTable dtable;
private void Form1_Load(object sender,EventArgs e)
{ // Creating Intance of DataTable
dtable = new System.Data.DataTable();
// Creating Instance to DataColumns
DataColumn dcid =new System.Data.DataColumn("ID",typeof(int));
DataColumn dcname =new System.Data.DataColumn("NAME",typeof(string));
DataColumn dcage =new System.Data.DataColumn("AGE",typeof(int));
DataColumn dccity =new System.Data.DataColumn("CITY");
// Adding Columns to DataTable
dtable.Columns.Add(dcid);
dtable.Columns.Add(dcname);
dtable.Columns.Add(dcage);
dtable.Columns.Add(dccity);
// Set AutoIncrement property to true
dcid.AutoIncrement =true;
// Set starting value for increment
dcid.AutoIncrementSeed = 11;
// Set increment value
dcid.AutoIncrementStep = 2;
// Binding DataGridView to DataTable
dataGridView1.DataSource = dtable;
}
}
}

Run the application.

Output

autoincrement in .net

Fill the textboxes

autoincrement propety

Click the "ok" button. You will note that you are not assigning any value for "ID". But when you click the button, It shows 11 as "ID" DataGridView. Because the
AutoIncrementSeed property is set to 11. Look at the following figure.

autoincrement

Again fill the textboxes with a value.

autoincrement in ado.net

Click the button. You will note that "ID" will be incremented by 2. Because the AutoIncrementStep property is set to 2. Which means it is incremented by 2. Look at the following figure.

autoincrement in ado.net

Here are some related resources.

Up Next
    Ebook Download
    View all
    Learn
    View all