Question

I have this piece of code which should be pretty straight forward.

private void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection sqlConn = new SqlConnection(connString))
            {
                sqlConn.Open();

                using (SqlDataAdapter da = new SqlDataAdapter())
                {
                    da.SelectCommand = new SqlCommand("SELECT Id, FirstName, LastName, TcReadOnly FROM PersonTable", sqlConn);

                    using (SqlCommandBuilder builder = new SqlCommandBuilder(da))
                    {                           
                        DataTable dt = (DataTable)dgvUsers.DataSource;

                        da.UpdateCommand = builder.GetUpdateCommand();
                        da.Update(dt);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Der er sket en fejl \r\n \r\n" + ex.ToString());
        }
    }

However, I recieve this error when the code is run.

enter image description here

Line 96 in Userform being

da.Update(dt);

I have already checked that my SelectCommand return a primary in Id, so that shouldn't be the problem.

Was it helpful?

Solution

Of course, seconds after asking the question I found the answer.

The SelectCommand I'm using to actually fill the DataTable looks like this

da.SelectCommand = new SqlCommand("SELECT Id, FirstName AS Fornavn, LastName AS Efternavn, " +
                        "TcReadOnly AS 'Read only' FROM PersonTable", sqlConn);

Which means that the columns in my DataTable doesn't have the same names as the ones I'm trying to update the database with :-) Brainfart....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top