从datagridview返回的空值

时间:2013-03-18 05:01:10

标签: c# c#-4.0 datagridview

我在数据库中有一个表,其中作者姓名与他们的Google引文一起存储。多个作者用逗号分隔。我将它们拆分并使用以下代码在数据网格视图中显示它们:

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是主键,所以它不能为空。在数据网格视图中,没有id为null,但在存储时,它会在一组作者被分割之后返回null id。我的意思是如果第一篇论文是由四位作者写的。它在4行之后立即返回null,然后在每个组之后返回。请帮忙

2 个答案:

答案 0 :(得分: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()); 
        }
  }

答案 1 :(得分:0)

尝试将您的单元格[index]更改为单元格[列名],我猜索引是您的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 +"');";