Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First execute a query to get the ID with ExecuteScalar. If it returns a not null value (meaning that you have found the Title) you have your ID. Else execute the insert of the new data.</p> <p>Meanwhile, do not use string concatenation to execute sql commands. (<a href="https://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain">SQL Injections</a>)</p> <pre><code>string sql2 = "Insert into tbDepartment ([Title], [Abbreviation]) values (@Desc, @DepCode)"; string sqlDep = "Select [ID] from tbDepartment where Title = @title" SqlCommand cmdDep = new SqlCommand(sqlDep, connection); cmdDep.Parameters.AddWithValue("@title", gridView3.GetRowCellValue(i, gridView3.Columns[DepCode]).ToString(); object result = cmdDep.ExecuteScalar(); if(result != null) { cmdDep.Parameters.Clear(); cmdDep.CommandText = sql2; cmdDep.Parameters.AddWithValue("@Desc", Convert.ToString(gridView3.GetRowCellValue(i, gridView3.Columns[DepDesc]); cmdDep.Parameters.AddWithValue("@DepCode", Convert.ToString(gridView3.GetRowCellValue(i, gridView3.Columns[DepCode])); cmdDep.ExecuteNonQuery(); } else int id = Convert.ToInt32(result); </code></pre> <p>A part from this, there is something that <strong>is not quite correct</strong> in your query above. You get the value to search for <code>Title</code> from <code>gridView3.GetRowCellValue(i, gridView3.Columns[DepCode])</code> But in the insert query you use this same grid cell to update the value for the column <code>Abbreviation</code> while the <code>Title</code> column is updated using another cell <code>gridView3.GetRowCellValue(i, gridView3.Columns[DepDesc]))</code> probably the correct insert text is:</p> <pre><code>string sql2 = "Insert into tbDepartment ([Title], [Abbreviation]) values (@DepCode, @Desc)"; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload