【发布时间】:2013-03-21 06:45:40
【问题描述】:
我有一个 SQLDataAdapter,在我的查询中我获取两个字段,ID(PK),名称。
我在我的数据适配器中注册了一个 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;
}
}
}
【问题讨论】:
-
显示你的完整代码..
-
更改列的可见性应该对 SqlCommandBuilder 生成的命令没有影响。你错过了什么。
-
ID 应该是
DataKeyNames而不是列。你应该能够写出类似的东西:this.dgvAttributes.DataKeyNames... -
@yigit Yener,但是效果很好,你可以自己试试这段代码。
-
@noobob,这个变化会有什么影响?这能解决我的问题吗?
标签: c# .net-4.0 sqlcommandbuilder