简体   繁体   中英

How to save my datagridview with c# winforms bounded to a datatable

I have bound my MSSQL datatable to a datagridview using the designer (the datatable has atleast 30 columns), it fills the data like this:

this.produktaiTableAdapter.Fill(this.veiklosDuomenysDataSet.Produktai);
this.produktaiBindingSource.Filter = advancedDataGridView1.Columns[1].HeaderText + " = " + Veiklos_ID;

It is necessary for me to bind it like this, as I have a lot of code concerning every single column in the DGV (for example, width, currencies, and so on).

Now I want to save all the new, updated, and deleted data in datatagridview to my MSSQL datatable by clicking a Save button. How can I do that? How can I convert my edited datagridview to the datatable?

I also tried this code on my save button click:

this.Validate();
this.produktaiBindingSource.EndEdit();
this.produktaiTableAdapter.Update(this.veiklosDuomenysDataSet.Produktai);

And.. It doesn't work. I am fairly new with datagridview and datatables overall as this problem I think should have an easy fix.

EDIT:

Also, could this line help somehow?

DataTable Produktai = advancedDataGridView1.DataSource as DataTable;

EDIT2: This doesn't work either.

veiklosDuomenysDataSet.Naudotojai.AcceptChanges();
this.Validate();
this.produktaiBindingSource.EndEdit();
this.produktaiTableAdapter.Update(this.veiklosDuomenysDataSet.Produktai);
MessageBox.Show("Data is saved!");

EDIT3:

This is a debug picture of my main form: Here

As you can see I have no textbox or buttons like INSERT, DELETE and UPDATE. The user can edit the DGV simply by clicking on a cell and editing the value, add new rows simply by pressing ENTER, deleting the row by clicking Delete (Ištrinti in picture) on the same selected row (NOTE: delete button column is the only unbound column in DGV).

I use MSSQL datatable to bound it with the datagridview, and I want all the rows that are new, deleted or edited in the datagridview to be renewed/updated in the datatable that it is bounded too by save button.

Maybe there should be something different with this information, a wild guess?

There's nothing wrong with the posted code in terms of "that's how you save" so the diagnosis needs to methodically chase things through:

  • Run the program, load data into the grid, edit some of it
  • Pause in the debugger just before you update, and call GetChanges on the datatable that is about to be saved
  • If there are no changes, then that table was not edited (the grid is bound to a different table) or no edits were made (the grid edit was cancelled not committed) or the edit's were reverted or accepted (RejectChanges or AcceptChanges was called on the datatable)
  • if there are changes move to capturing the return value from tableadapter update (Write var x = tableadapter.update(..) ) and step the debugger over the call to update
  • if the result is 0 then no rows were updated; this should result in a concurrencyexception if there were changes and the tableadapter query is enabled for concurrency (probably the default). If your tableadapter doesn't have an update query built in then again you should get an exception if you try to save edits ("update requires a valid updateconmand when passed a collection with modified rows". If it's just 0 and no exception is thrown then for some reason no rows were updated - not a situation I'd expect and would need some more investigation
  • if the result is > 0 then an update was made (changes were saved). On a tableadapter the Update method is responsible for all inserts, updates and deletes. If you can't see your changes it you're most likely looking in the wrong database file, or your build process is erasing your file and replacing it with a new one. This most often happens with file based databases like Access but can happen with sql server if your database file is being dynamically attached and detached

Start over - this will generate a basis for comparison

I didn't encounter any problems saving when I did:

  • Make a new project
  • Open server explorer, add a connection
  • Choose SQLServer file driver, put a path to a new file (new.mdf), click OK, say yes to create it
  • Expand the new node in server explorer, right click tables, add a new table with column names that are sensible (just letters and numbers, no spaces, no punctuation or other symbols - you could add percent signs etc and it'll still work, but there's a reason why no-one does it, and that's because it makes life very hard work all down the line. If you think want a column called "Profit %" call it "ProfitPercent" instead). Save the table.
  • Open data sources tool panel, add a new datasource, choose database, choose dataset, choose the connectionstring for new.mdf
  • Really carefully read the next question it asks . Do not just skip past it. If you say Yes then, by default your program will dynamically attach a database that gets erased and replaced every time you run the program (but this is typically what you want). If you say No, then understand that the db your program edits might not be in the project folder at all
  • Tixk the table in the wizard, or close the wizard and drag the new table out of server explorer into the dataset. Save the dataset
  • Open the form, drag the table representation out of the data sources tool panel and onto the Form. A datagridview appears
  • Run the program, add some rows, click the save button
  • Stop the program, run it again - the rows will be there if you said No to the important question earlier. If you said Yes, then stop the program, click the new.mdf file in the Solution Explorer, change "Copy Always" to "Copy if Newer", run the program again. Add rows, save, stop the program and run it again, the rows will be there. The only time they will disappear is if you change the design of the new.mdf database (so that it is newer)

Your form code will now just be something like:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void myTableBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        this.Validate();
        this.myTableBindingSource.EndEdit();
        this.tableAdapterManager.UpdateAll(this.newDataSet);

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'newDataSet.MyTable' table. You can move, or remove it, as needed.
        this.myTableTableAdapter.Fill(this.newDataSet.MyTable);

    }
}

And you won't have written any of it. It's all that's required to load, show, edit and save data using a datagridview. The call to tableAdapterManager.UpdateAll is equivalent to someTableAdapter.Update - a tableadaptermanager is a convenience device that calls Update in the correct order to ensure that parent rows are created before related child rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM