Can't read data from database
Xamarine
Moble appSelect from database id and name
Two fields
Error
System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
My code
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 AnsariPosted Oct 16, 2023, 9:45 AM
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:
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.