从datagridview返回空值
本文关键字:空值 返回 datagridview | 更新日期: 2023-09-27 18:04:30
我在数据库中有一个表,其中存储了作者姓名以及他们的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为空。因为id是主键,所以它不能为空。在数据网格视图中,没有id为空,但在存储中,它在一组作者被拆分后立即返回空id。我的意思是,如果第一篇论文是由四个作者写的。它在4行之后返回null,然后在每个组之后返回null。请帮助
需要正确调试代码并查看完整代码以给出此行为的确切原因,但如果您只是想使其工作,请尝试此
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());
}
}
尝试改变你的单元格[索引]到单元格[列名],我猜索引的原因是你的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 +"');";