2013-03-21 65 views
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; 
      } 


     } 


    } 
+0

顯示完整的代碼.. – 2013-03-21 06:49:24

+0

更改列可見性應該對SqlCommandBuilder生成的命令沒有影響。你錯過了一些東西。 – 2013-03-21 07:15:05

+0

該ID應該是一個'DataKeyNames'而不是一列。你應該可以寫下如下內容:this.dgvAttributes.DataKeyNames ... – noobob 2013-03-21 07:18:41

回答

0

這是AutoGeneratedCommands問題。在觸發更新之前,它們要求每個屬性都分配一個適當的值。

您可以採用以下任一操作:

  1. 修改列DimensionID接受空值;或

  2. 將您自己的更新SP寫入數據庫,並將其註冊爲UpdateCommand與您的數據適配器。

希望這會告訴你路徑。