I have a datagrid where I want to display a list of database locations found on the computer and their owner. I try to to this by setting the ItemSource
of the DataGrid to an ObservableCollection
. I then execute a method that obtains a list of all databases. I then execute another method try and split and build the ObservablCollection
and that is where I seem to get my errors.
When I call the content page that has the DataGrid this is the constructor:
SQLiteAsyncConnection _connection;
public ObservableCollection<DbsSelect> dbs { get; set; } = new ObservableCollection<DbsSelect>();
public string RetVal { get; set; }
List<string> dbList = new List<string>();
public SelectDb(List<string> dbs)
{
dbList = dbs;
InitializeComponent();
BindingContext = this;
GetSettings();
}
The GetDbs() method looks like this:
public List<string> GetDbs()
{
var files = new List<string>();
var dirs = new string[] { };
foreach(DriveInfo d in DriveInfo.GetDrives().Where(t => t.IsReady == true))
{
try
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "LakDb_*.db", SearchOption.TopDirectoryOnly));
dirs = Directory.GetDirectories(d.RootDirectory.FullName);
}
catch (UnauthorizedAccessException)
{
// Do Nothing And Continue.
}
foreach(var DirVar in dirs)
{
try
{
files.AddRange(Directory.GetFiles(DirVar, "LakDb_*.db"));
}
catch (UnauthorizedAccessException)
{
// Do Nothing.
}
}
}
return files;
}
Next I executed a method that tries to assemble a List<string>
and I want to add it into the ObservableCollection
like this:
private async void GetSettings()
{
List<string> dataList = new List<string>();
string? dir = string.Empty;
foreach (var item in dbList)
{
var Options = new SQLiteConnectionString(item, true);
_connection = new SQLiteAsyncConnection(Options);
var query = _connection.Table<LakSettings>().Where(t => t.Id == 1);
LakSettings settings = query.FirstOrDefaultAsync().Result;
dir = Path.GetDirectoryName(item);
dataList.Add(dir);
dataList.Add(item);
dataList.Add(settings.DbOwner);
}
// This is where I'm getting the error
ObservableCollection<DbsSelect> dbs = new(dataList as List<DbsSelect>);
dbLst.ItemsSource = dbs;
}
So where am I going wrong? is there a better way to set the ItemSource for the DateGrid?