1
我有一个SQLDataAdapter,在我的查询中我提取了两个字段,ID(PK),Name。SQL命令生成器查询值
我注册了一个sql命令生成器到我的数据适配器,所以我不必编写查询来更新数据库中的表。
当我调用da.update()
方法时,由于此错误,sql会抛出无法将null插入到DimensionID的错误,因此我必须在我的数据集中选择此字段,然后使用适当的值将此字段填充到网格中。然后da.update()
工作。
现在的问题是,我不希望此字段出现在我的网格中,当我将其可见属性设置为false时,命令构建器在查询中省略此列。为了解决这个问题,我必须将列宽设置为0,但我的网格中仍然有一条小线。
有没有更好的方法来处理这种情况?除了我手动编写查询。
下面是代码填充网格;
private void frmAttributes_Load(object sender, EventArgs e)
{
ds.Tables.Add("Attributes");
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
cmd.CommandText = "select ID,Attribute,Code,DimensionID from DimensionAttribute where dimensionid = " + SelectedAttribute;
da.SelectCommand = cmd;
cb.DataAdapter = da;
da.Fill(ds,"Attributes");
this.dgvAttributes.DataSource = ds.Tables["Attributes"];
this.dgvAttributes.Columns["ID"].Visible = false;
this.dgvAttributes.Columns["DimensionID"].Width = 0;
}
,这里是更新按钮后面的代码:
private void btnOk_Click(object sender, EventArgs e)
{
if (ds.HasChanges())
{
DialogResult d = new DialogResult();
d = MessageBox.Show("Are you sure you want to save changes to database?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (d == DialogResult.Yes)
{
try
{
fillDimensionID();
da.UpdateCommand = cb.GetUpdateCommand();
da.InsertCommand = cb.GetInsertCommand();
da.DeleteCommand = cb.GetDeleteCommand();
da.Update(ds,"Attributes");
this.DialogResult = DialogResult.OK;
this.Close();
}
catch (Exception)
{
throw;
}
}
else
{
return;
}
}
}
显示完整的代码.. – 2013-03-21 06:49:24
更改列可见性应该对SqlCommandBuilder生成的命令没有影响。你错过了一些东西。 – 2013-03-21 07:15:05
该ID应该是一个'DataKeyNames'而不是一列。你应该可以写下如下内容:this.dgvAttributes.DataKeyNames ... – noobob 2013-03-21 07:18:41