我有一个数据库表(在本例中为空)
create table words
(
id int not null,
word nvarchar(50) not null
)
和DataGridView
,我就是这样填写的:
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);
}
然后我用一些值填充一行_ tblWords 并调用Update()
。得到这个消息:
抛出异常:' System.Data.SqlClient.SqlException'在 System.Data.dll
附加信息:无法将值NULL插入列' id',table' DB.MDF.dbo.words&#39 ;;列不允许空值。插入 失败。
为什么' id'是不是从DataTable中获取的?我做错了什么?
更新: 在Update()函数的开头插入此代码后,一切正常:
private void Update()
{
_wordsDataTable.Rows.Clear();
_wordsDataTable.Rows.Add(0, "xxx");
...
因此,只有在通过DataGridView填充DataTable时才会出现问题。为什么呢?!
答案 0 :(得分:0)
我猜这个问题与DataGridView中的最后一个空行有关。
你可以尝试这样的事情而不是最后的_wordsAdapter.Update(_wordsDataTable);
行
var haveDbNull = _wordsDataTable.Rows.Cast<DataRow>().ToLookup(r => r.ItemArray.Contains(DBNull.Value));
Debug.Print("have DbNull values: " + haveDbNull[true].Count()); // check this number in the Debug Output window
Debug.Print("don't have DbNull values: " + haveDbNull[false].Count());
_wordsAdapter.Update(haveDbNull[false].ToArray()); // to update just the rows that dont have DBNull values
答案 1 :(得分:0)
我找到了一些解决方案。我只是删除添加的行并以编程方式添加相同的值。
object[] rowValues = dt.Rows[row].ItemArray;
dt.Rows.RemoveAt(row);
dt.Rows.Add(rowValues);
有没有人知道这种不那么丑陋的方式呢?
答案 2 :(得分:0)
解决方案一如既往地非常简单......
_dtWords.EndInit();