DiH DiH - 4 months ago 7
Android Question

How can i add two columns from sql to listview?

i'm using this code:

var listview1 = FindViewById<ListView>(Resource.Id.InventoryList);
var adapter = new ArrayAdapter<object>(this, Android.Resource.Layout.SimpleListItem1);
listview1.Adapter = adapter;

con.Open();

SqlCommand sqlCmd = new SqlCommand("SELECT Name,Code from Inventory", con);

SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
adapter.Add((string)sqlReader["Name"+"Code"]);

}
sqlReader.Close();
con.Close();


I'm getting an error:System.IndexOutOfRangeException: Index was outside the bounds of the array.

Answer

Since sqlReader is a map, you should do something like:

 adapter.Add(sqlReader["Name"].ToString() + " - " + sqlReader["Code"].ToString());

You can't concatenate two keys (sqlReader["Name"+"Code"]) and expect two concatenated values to be returned.

Comments