2015-10-05 61 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

这工作!非常感谢你。此外,您使用括号而不是括号。我加入了一个编辑来纠正这个问题。 –