I have a DB table (which is empty in this example)
create table words
(
id int not null,
word nvarchar(50) not null
)
and a DataGridView
which I'm filling like that:
private SqlConnection _conn;
private SqlDataAdapter _wordsAdapter;
private DataTable _wordsDataTable = new DataTable();
private DataGridView _tblWords;
private void FillWords()
{
_wordsAdapter = new SqlDataAdapter(new SqlCommand("select id, word from words", _conn));
_wordsAdapter.Fill(_wordsDataTable);
DataGridViewColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "id";
column.Name = "id";
_tblWords.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "word";
column.Name = "word";
_tblWords.Columns.Add(column);
_tblWords.DataSource = _wordsDataTable;
}
private void Update()
{
_wordsAdapter.InsertCommand = new SqlCommand("insert into words (id, word) values (@id, @word)", _conn);
SqlParameter p = _wordsAdapter.InsertCommand.Parameters.Add("@id", SqlDbType.Int);
p.SourceColumn = "id";
p.SourceVersion = DataRowVersion.Original;
p = _wordsAdapter.InsertCommand.Parameters.Add("@word", SqlDbType.NVarChar);
p.SourceColumn = "word";
p.SourceVersion = DataRowVersion.Original;
_wordsAdapter.Update(_wordsDataTable);
}
Then I fill a single row of _tblWords with some values and call Update()
. And get this message:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Additional information: Cannot insert the value NULL into column 'id', table 'DB.MDF.dbo.words'; column does not allow nulls. INSERT fails.
Why the value for 'id' is not taken from DataTable? What am I doing wrong?
UPDATE: After inserting this code in the beginning of Update() function, everything works fine:
private void Update()
{
_wordsDataTable.Rows.Clear();
_wordsDataTable.Rows.Add(0, "xxx");
...
So the problem only appears when I fill the DataTable through DataGridView. Why?!