2013-03-18 81 views
0

我在數據庫中有一個表,其中作者姓名與他們的Google引文一起存儲。多個作者用逗號分隔。我將它們分割,並使用此代碼並將它們顯示在數據網格視圖:從datagridview返回空值

foreach (DataRow row in dataTable.Rows) 
{ 
    int GSCitations; 
    { 
     string paper = Convert.ToString(row[1]); 
     Int32.TryParse(Convert.ToString(row[2]), out GSCitations); 
     string str = Convert.ToString(row[0]); 
     string[] result = str.Split(new Char[] { ',' }); 
     foreach (string author in result) 
     { 
      dataGridView1.Rows.Add(id, author, paper, GSCitations); 
      id++; 
     } 

    } 

然後我去接他們從數據網格視圖,並嘗試使用此代碼將它們存儲在數據庫中:

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
     try 
     { 
     mysqlStatement = "INSERT INTO test1(ID, Authors,Paper, GSCitations) VALUES('" + row.Cells[0].Value + "','" + row.Cells[1].Value + "','" + row.Cells[2].Value + "','" + row.Cells[3].Value +"');"; 
     mySqlCommand = new MySqlCommand(mysqlStatement, mySqlConnection); 
     mySqlCommand.ExecuteNonQuery();  
     } 

     catch(Exception excep) 
     { 
     MessageBox.Show(excep.ToString()); 
     } 
    } 

但拋出異常,該id爲null。因爲ID是主鍵它不能B空。在數據網格視圖中,沒有id爲空,但是在存儲時,它返回null id,正好在一組作者被分割之後。我的意思是如果第一篇論文由四位作者撰寫。它在4行之後立即返回null,並且在每個組之後都是如此。請幫助

+2

幾件事情(但不相關)*,先用[參數化查詢(HTTP: //www.dotnetperls.com/sqlparameter)而不是連接查詢。其次,如何再次使用相同的主鍵插入數據庫?你想更新嗎? – Habib 2013-03-18 05:04:36

+0

ID的價值是什麼?它是空的嗎?數據庫表是空的嗎? – 2013-03-18 05:13:45

+0

我每次運行代碼時都會截斷表格,我這樣做只是爲了檢查目的 – mani 2013-03-18 05:19:03

回答

0

嘗試烏爾細胞[指數]改爲細胞[列名],我猜指數的原因是Y在您的ID列返回NULL

mysqlStatement = "INSERT INTO test1(ID, Authors,Paper, GSCitations) 
VALUES('" +row.Cells[YOUR COLUMN NAME].Value + "','" + 
row.Cells[YOUR COLUMN NAME].Value + "','" + 
row.Cells[YOUR COLUMN NAME].Value + "','" + 
row.Cells[YOUR COLUMN NAME].Value +"');"; 
+0

因爲他試圖插入一些不存在的數據庫?所以他得到了空值? – 2013-03-18 05:56:15

+0

,但它表明他們在datagridview中沒有空值 – mani 2013-03-18 14:35:51

+0

列名沒有幫助 – mani 2013-03-18 14:36:19

1

需要正確調試代碼,看看完整的代碼給這種行爲的確切原因,但如果你只是想使它工作嘗試在你的代碼*此

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
     if(row == null || row.Cells[0].Value == null) 
      continue; 

     try 
     { 
      mysqlStatement = "INSERT INTO test1(ID, Authors,Paper, GSCitations) VALUES('" + row.Cells[0].Value + "','" + row.Cells[1].Value + "','" + row.Cells[2].Value + "','" + row.Cells[3].Value +"');"; 
      mySqlCommand = new MySqlCommand(mysqlStatement, mySqlConnection); 
      mySqlCommand.ExecuteNonQuery();  
     } 

     catch(Exception excep) 
     { 
      MessageBox.Show(excep.ToString()); 
     } 
    } 
+0

不!我已經嘗試過,但這不是好的方法,我有3個lac記錄意味着循環將至少返回2個空值,因此它會產生巨大的差異。我想修復它 – mani 2013-03-18 14:29:45