Can't read data from database
Xamarine
Moble appSelect from database id and name
Two fields
Error
C#
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'My code
C#
private async void LoadNotes()
{
MySqlConnection conn = new MySqlConnection(Constants.connectionString);
await conn.OpenAsync();
MySqlCommand cmd = new MySqlCommand(Constants.selectAllQuery, conn);
cmd.Connection = conn;
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
notes.Add(rdr[0]);
notes.Add(rdr[1]);
}
rdr.Close();
lstNotes.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleExpandableListItem1, notes);
}
}
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Oct 16, 2023, 5:45 AM EDT
The error System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' indicates that you are trying to access an index in an array that does not exist. This is likely happening in the part of the code where you are accessing the elements from the rdr object. It's important to ensure that the index you are accessing is within the bounds of the array.
Here's a revised version of your code that ensures the indices are within the bounds of the array:
private async Task> LoadNotes() { List notes = new List(); try { using (MySqlConnection conn = new MySqlConnection(Constants.connectionString)) { await conn.OpenAsync(); using (MySqlCommand cmd = new MySqlCommand(Constants.selectAllQuery, conn)) { using (MySqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { // Check if the columns are not null if (!rdr.IsDBNull(0)) { notes.Add(rdr.GetString(0)); // Assuming the first column is of type string } if (!rdr.IsDBNull(1)) { notes.Add(rdr.GetString(1)); // Assuming the second column is of type string } } } } } } catch (MySqlException ex) { // Handle the exception or log the error Console.WriteLine("Error: " + ex.Message); } return notes; }Make sure, before accessing the data from the reader, we check whether the index is valid and the value is not null using the IsDBNull method. Make sure the indices 0 and 1 correspond to the existing columns in your database. Also, make sure that the data types retrieved match the types you are trying to store in the notes list.