Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

How to update data from DataGridView with one column to database with two columns? ERROR - Cannot insert value NULL

$
0
0
I'm trying to update data from `DataGridView` to my database. While I was looking for the solution of this problem on google, I noticed that all of the solutions are managed by using class variables (for `DataTable`,`SqlDataAdapter`,...). I'm trying to do this just by using function variables.

This is how I loaded data to `DataGridView`:

   
private void LoadDataGridView(int ID)
{    try    {         SqlConnection connection = new SqlConnection(connString);         SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID = @ID",connection);         cmd.Parameters.Add("@ID",SqlDbType.Int).Value = ID;         DataTable dataTable = new DataTable();         SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);         dataAdapter.Fill(dataTable);         DataGridView.DataSource = dataTable;    }    catch (Exception)    {         MessageBox.Show("ERROR WHILE CONNECTING TO DATABASE!");    }
}



`DataGridView` is showing just those sentences that match particular ID.

This is what I have tried so far:

 

private void RefreshBtn_Click(object sender, EventArgs e)   

{

try

{              SqlConnection connection = new SqlConnection(connString);              SqlCommand cmd = new SqlCommand("SELECT SENTENCEFROM Sentences WHERE CategoryID IN(@CategoryID)", connection);              cmd.Parameters.Add("@CategoryID",SqlDbType.Int).Value = CategoryID;              SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);              SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);              dataAdapter.Update(dataTable);        }        catch (Exception)        {              MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");        }    }




This is the error that comes up:
>Cannot insert value NULL into column CategoryID, table ...;column does not allow nulls.Insert fails. The statement has been terminated.

  



Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>