Populate datagridview without binding to a data source

katz

Member
Joined
May 24, 2013
Messages
6
Programming Experience
Beginner
I've got some data in a database that I need to display in a datagridview. So far so trivial, but I also want the user to be able to add and delete rows from the datagridview, and of course they can't while it's data bound. So the question is: How would you go about getting data from a database into a datagridview without it being data bound at the end?

(I've come up with a few solutions, but they're unwieldy and work poorly; eg, create a new hidden datagridview, populate that from the database, then copy the data over one row at a time. But there's got to be a better way.)
 
I also want the user to be able to add and delete rows from the datagridview, and of course they can't while it's data bound.
Um, who told you that? Of course they can. What can't happen is you adding rows to and removing rows from the grid directly while it's bound. If you want to add or remove a row in code then you must do so via the data source. The user can certainly do so via the UI though. By default, the bottom row of the grid does not actually represent an existing record but is there specifically for the user to type into to create a new row. As for deleting, the user simply selects a row and hits the Delete key. It's that simple.
 
No, no, I don't want to change the data source. I only want to change the data in the table.
I'm afraid that you're not really making sense. You retrieve data from the database into a DataTable and you bind that DataTable to the DataGridView. The user can then add, edit and delete rows in the grid and those changes will be automatically pushed to the DataTable, which is the whole point of data-binding. The DataTable is detached from the database though, so the database is unchanged at that point. You would then use the same data adapter or table adapter to Update the database with the changes as you used to Fill the DataTable with data in the first place.
 
Huh.

The datatable is declared in a (public) subroutine and it isn't static. I thought it should be unavailable outside that subroutine.
 
Last edited:
DataTables aren't declared. No objects are declared. Objects are created and they don't have a scope. What you're talking about is a variable. Variables do have scope. If you have declared a DataTable variable in a method then it's quite true that that variable cannot be accessed outside that method. That doesn't mean that the DataTable object assigned to that variable can't be though. The same object can be assigned to as many different variables as you like. That method can assign the same DataTable object to another variable or property that is accessible from elsewhere or the method might return the DataTable object, so the caller can access it via the return value. If the method assigns the DataTable to the DataSource property of the grid then it can be accessed from there.
 
Back
Top