mani
mani

Reputation: 133

Null value returning from datagridview

I have a table in data base,In which authors names are stored along with their Google citations. multiple authors are separated by comma. I split them and show them on data grid view using this code:

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++;
        }

   }

then i pick them from data grid view and tried to store them in data base using this code:

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()); 
        }
  }

But it throws exception, that id is null. as id is primary key it cant b null. in data grid view no id is null, but in storing it returns null id, right after one group of authors is splitted.I mean if first paper is writen by four authors. it returns null right after 4 rows and then so on after every group. please help

Upvotes: 0

Views: 1732

Answers (2)

Pawan Nogariya
Pawan Nogariya

Reputation: 9000

Need to properly debug the code and see the full code to give the exact reason of this behavior, but if you just want to make it work try this

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()); 
        }
  }

Upvotes: 1

Chee mun Low
Chee mun Low

Reputation: 138

Try to change ur cells[index] to cells[column name], i guess the index is the reason y your ID column return 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 +"');";

Upvotes: 0

Related Questions