Sapster77
Sapster77

Reputation: 53

Can't update SQL from WPF datagrid

In my WPF (C#) application I am trying to update my SQL database when changes are made to a datagrid in the app. Displaying the dataset in the Datagrid works fine, but I can not get updates made in the datagrid sent back to the database.

This is what I have so far - The issue is, that I can't figure out how to pass the dataset (ds) and the sqladapter (sea) to the BtnSave_Click void, which should update the SQL with the changes made (I get a "Mainwindow does not contain a definition for 'ds'). I have been using VB.Net previously and there I could declare them as public variables, but that can't be done here I guess. I have read that I could declare a static class and put them there, but also that that is a bad technique. I am very thankful for any suggestions on how to proceed. Cheers, Peter.

public partial class MainWindow : Window
{
  


    public MainWindow()
    {
        InitializeComponent();
       
    }
    
    private void grdSchedule_Loaded(object sender, RoutedEventArgs e)
    {
        
        string strCon = ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;
        string CmdString = string.Empty;
        using (SqlConnection con = new SqlConnection(strCon))
        {
            CmdString = "SELECT * FROM tbl_Schedule";
            SqlCommand cmd = new SqlCommand(CmdString, con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            sda.TableMappings.Add("Table", "tbl_Schedule");
            DataSet ds = new DataSet("tbl_Schedule");
            sda.Fill(ds, "tbl_Schedule");
            grdSchedule.ItemsSource =ds.Tables["tbl_Schedule"].DefaultView;
            ds.AcceptChanges();
        }
    }

    private void btnSave_Click(object sender, RoutedEventArgs e)
    {
        DataSet changes = this.ds.GetChanges();
        if (changes != null)
        {
            //Data has changes. 
            //use update method in the adapter. it should update the datasource
            int updatedRows = this.sda.Update(changes);
            this.ds.AcceptChanges();
        }

    }

}

}

Upvotes: 0

Views: 162

Answers (1)

Anton
Anton

Reputation: 748

For save changes via sqlDataAdapter you need to specify commands for properties UpdateCommand, DeleteCommand, InsertCommand.

Also need notice that such commands must contains parameters which will be binded to columns in your DataTable.

var updateCommand = new SqlCommand("Update tbl_schedule set OperationId=@OperationId where Id=@Id")
updateCommand.Parameters.Add("@OperationId", SqlDbType.int, "OperationId")
updateCommand.Parameters.Add("@Id", SqlDbType.Int, "Id");
sda.UpdateCommand = updateComand;

Upvotes: 1

Related Questions