user2852283 user2852283 - 2 months ago 18
C# Question

Get AutoNumber column index in Ms Access 2010/2013

(first sorry for my English):

I want to temporarily change

auto-number
column to
int64
data type to import records from another database. After importing the records, I want to change it back to
auto-number
.

My Problem:
I try to use the
table.Columns[i].AutoIncrement
property to check if this column is
auto-number
and get its index so that I can change its datatype, but this property didn't work for me, it returned false for all columns.

I work with 2010/2013 Access database.

So I want to know what to do to get index of
auto-number
column?

Answer

You can use this approach

// Bogus query, we don't want any record, so add a always false condition
OleDbCommand cmd = new OleDbCommand("SELECT * FROM aTable where 1=2", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable test = new DataTable();
da.FillSchema(test, SchemaType.Source);
for(int x = 0; x < test.Columns.Count; x++)
{
    DataColumn dc = test.Columns[x];
    Console.WriteLine("ColName = " + dc.ColumnName + 
                      ", at index " + x +
                      " IsAutoIncrement:" + dc.AutoIncrement);
}