Search code examples
c#datagridviewsqlconnectionsqlcommand

Saving edits to database made in datagridview


How can I adapt my code to any changes that are made remain persistent?

As I understand I need to update the datatable which in turn will update the database. So I have tried to use the update command like below on a button click event.

adb.Update(dt);

However this doesn't seem to work, so I am obviously missing something, but I'm not sure what?.

Code

String ConnStr = "Data Source=database.com\\sqlexpress; Initial Catalog=Data; User ID=mobile; Password=password";
String SQL = "SELECT stationID, LocationName, plandate, username, status  FROM dbo.joblist WHERE username = @username and status = @status";

SqlConnection con = new SqlConnection(ConnStr);

try
{
    con.Open();
}
catch (Exception)
{
    MessageBox.Show(e.ToString());
}

SqlCommand command = new SqlCommand(SQL, con);
command.Parameters.Add("@username", SqlDbType.VarChar).Value = auditorCmb.Text;
command.Parameters.Add("@status", SqlDbType.VarChar).Value = statusCmb.Text;

SqlDataAdapter adb = new SqlDataAdapter(command);

using (DataTable dt = new DataTable())
{

    try
    {
        adb.Fill(dt);
        dataGridView1.AutoResizeColumns();
        dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        con.Close();
    }
    catch
    {
        MessageBox.Show(e.ToString());
    }
    dataGridView1.DataSource = dt;
}

Solution

  • As far as I know SqlDataAdapter does not generate insert, update or delete commands on its own.

    You have to either set them manually - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx.

    Or generate them with SqlCommandBuilder:

    public static DataSet SelectSqlRows(string connectionString,
        string queryString, string tableName)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand(queryString, connection);
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
    
            connection.Open();
    
            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet, tableName);
    
            //code to modify data in DataSet here
    
            builder.GetUpdateCommand();
    
            //Without the SqlCommandBuilder this line would fail
            adapter.Update(dataSet, tableName);
    
            return dataSet;
        }
    }