read inserted Identity value

D

Danko Greiner

I'm trying to update every table in DataSet, but getting inserted "id_user"
gets me an exception:
column "id_user" is read only

if(_dataSet.HasChanges())
{
SqlDataAdapter _adapter;
SqlCommandBuilder _builder;
SqlConnection conn = new
SqlConnection(GlobalSettings.ConnectionString);
conn.Open();
foreach(DataTable dt in _dataSet.Tables)
{
string selectString = "SELECT * FROM " + dt.TableName;
_adapter = new SqlDataAdapter(selectString, conn);
_builder = new SqlCommandBuilder(_adapter);
_adapter.RowUpdated += new
SqlRowUpdatedEventHandler(_adapter_RowUpdated);
_adapter.Update(dt);
}
}


private void _adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{

SqlCommand command = new SqlCommand("SELECT @@IDENTITY",
e.Command.Connection);
object o = command.ExecuteScalar();
e.Row.Table.Columns["id_osoba"].ReadOnly = false;
e.Row["id_user"] = o;
e.Row.AcceptChanges();
} conn.Close();


Please make comments about this code, but my prime problem is WHY do i get
an exception:
"column 'id_user' is read only"???
of course it's read only, it's Identity column, but everywhere i look, thi
is recommended way to retrieve inserted Identity

Thax for help.
 
F

Fitim Skenderi

How is your table declared ?

If your field ("id_user") is Identity (presuming your table is in MSSQL
database) then you cannot write data to the field, the value is
automatically assigned by MSSQL.

Fitim Skenderi
 
M

Miha Markic [MVP C#]

Hi Danko,

I suggest you to avoid using SqlCommandBuilder and rather create sql
commands by hand.
The insert statement would look something like: INSERT INTO table (...)
VALUES (...); SELECT SCOPE_IDENTITY() As Id (assuming Id is your pk)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top