2015-10-05 64 views
0

我正在使用DataGridView控件與DataTable組合來編輯SQL表。我有兩個表格中的複選框,分別綁定到bit not null SQL列acoustichud。當我添加一個新行並保持未選中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列的這個問題?

回答

1

您可以設置DataColumn.DefaultValueacoustichud

tbl.Columns["acoustic"].DefaultValue = false; 
tbl.Columns["hud"].DefaultValue = false; 

也許在SQL服務器,以便僅出現在hud領域的錯誤,你已經設置acoustic默認值。

+0

這工作!非常感謝你。此外,您使用括號而不是括號。我加入了一個編輯來糾正這個問題。 –