I have a Winforms TreeView and I wish to store the node data into an SQLite table, so that I can restore the TreeView when the application starts up next time. I use the TreeView to drive most of the desktop application and use index pointer fields within a class attached to the TreeNodes to access other tables in the database when a user clicks on a node.
The problem I am trying to avoid is a lot of “round tripping” between the TreeView and the TreeNode_Table everytime a new TreeNode is created. It would be best if I know ahead of time what the next autoincrement primary key will be in the TreeNode_Table before I create the TreeNode. That way I can create and add the node to the tree then copy the data into a new TreeNode_Table row in a single pass. No round trips between the table and the TreeView to sync up values like the primary key, node level, node index, and other node and row values.
I tried:
string strFindLastRowInserted = @"SELECT MAX([id]) FROM [TreeNode_Table];";
var findLastRowInsertedCmd = new SQLiteCommand(strFindLastRowInserted, _cnn);
object resultObj = findLastRowInsertedCmd.ExecuteScalar();
findLastRowInsertedCmd.Dispose();
if( resultObj != null)
NodeTagDataObj.DataPtr = (long)resultObj + 1;
But adding one to MAX([id]) breaks down if some of the most recently created nodes/rows have been previously deleted. I’m using the System.Data.Sqlite library to access the data file.
Thank you for your help. Any ideas?
I finally figured this out by probing around within Sqlite’s table metadata. To reliably obtain the next autoincrement key value before the new row is created, the following SQL can be used:
I added and tested the following static helper method to my SqliteHelper class and everything works as expected and the logic survives recent row deletions, disconnections, and application restarts.
SqliteHelper.cs:
I hope that others will find this useful…
-DougC