0
我正在使用DataGridView控件與DataTable組合來編輯SQL表。我有兩個表格中的複選框,分別綁定到bit not null
SQL列acoustic
和hud
。當我添加一個新行並保持未選中hud
列時,出現下面的錯誤。不要緊,我將acoustic
列設置爲。如果我檢查hud
列,但不選中acoustic
列,它可以正常工作。無法插入空數值使用DataGridView和DataTable
無法將值NULL插入列'hud',表'rawVinyl';列不允許有空值。 INSERT失敗。
該表的定義是:
CREATE TABLE rawVinyl
(
storesId nvarchar(12) NOT NULL,
baseColor nvarchar(50) NOT NULL,
shadeColor nvarchar(50) NULL,
rollWidth float NOT NULL,
shadeHeight float NULL,
acoustic bit NOT NULL,
hud bit NOT NULL
)
這是設計器生成的代碼,我遇到的麻煩的複選框。 acoustic
列的代碼與更改的名稱完全相同。
private System.Windows.Forms.DataGridViewCheckBoxColumn hud;
...
this.hud = new System.Windows.Forms.DataGridViewCheckBoxColumn();
...
this.hud.DataPropertyName = "hud";
this.hud.HeaderText = "H.U.D.";
this.hud.Name = "hud";
this.hud.Width = 46;
填充的DataGridView的代碼是
private const string selectQuery = "SELECT storesId, baseColor, shadeColor, rollWidth, shadeHeight, acoustic, hud FROM rawVinyl ORDER BY storesId";
...
DataTable tbl = new DataTable();
using(SqlDataAdapter data = new SqlDataAdapter(selectQuery, Global.ConnectionString))
{
data.Fill(tbl);
bindingSource1.DataSource = tbl;
}
最後但並非最不重要的,代碼保存更改爲:
DataTable tbl = bindingSource1.DataSource as DataTable;
DataTable changes = tbl.GetChanges();
if(changes != null)
{
using(SqlDataAdapter sda = new SqlDataAdapter(selectQuery,Global.ConnectionString))
using(SqlCommandBuilder scb = new SqlCommandBuilder(sda))
{
sda.UpdateBatchSize = 0; // do it all at once.
sda.Update(changes);
tbl.AcceptChanges();
}
}
我也試着設置爲默認值複選框列如下,但它沒有做出一點區別:
this.hud.FalseValue = false;
this.hud.IndeterminateValue = false;
this.hud.TrueValue = true;
我不明白的主要原因是爲什麼我沒有acoustic
列的這個問題?
這工作!非常感謝你。此外,您使用括號而不是括號。我加入了一個編輯來糾正這個問題。 –