private void AddQueryButton_Click(object sender, EventArgs e) { // Find a name like "query1", "query2", etc. that doesn't exist in the notebook and isn't to be imported. // First make a list of all the existing names that start with "query" so we can avoid them. var notebook = _manager.Notebook; List <string> existingNames = new(); using (var sdt = notebook.Query("SELECT name FROM sqlite_master")) { foreach (var row in sdt.Rows) { var name = (string)row[0]; if (name.StartsWith("query", StringComparison.OrdinalIgnoreCase)) { existingNames.Add((string)row[0]); } } } foreach (DataRow row in _dataTable.Rows) { var t = (SourceTable)row["source_table"]; existingNames.Add(t.TargetTableName); } // Count up until we find a unique name. string targetName; for (var i = 1; ; i++) { var proposedTargetName = $"query{i}"; if (!existingNames.Any(x => x.Equals(proposedTargetName, StringComparison.OrdinalIgnoreCase))) { targetName = proposedTargetName; break; } } // Ask the user for a query. DatabaseImportCustomQueryForm f = new(_session, targetName, "SELECT * FROM "); var result = f.ShowDialog(this); Focus(); if (result != DialogResult.OK) { return; } // Add a SourceTable to the list for this query. Check it by default. var sourceTable = SourceTable.FromSql(f.Sql, f.TargetName); var newRow = _dataTable.NewRow(); newRow["source_table"] = sourceTable; newRow["display_name"] = sourceTable.DisplayText; newRow["to_be_imported"] = true; _dataTable.Rows.Add(newRow); }