user6453809 user6453809 - 4 months ago 24
Android Question

How to read from Sql Column To Spinner?

I want to read an sql column and fill a Spinner. I'm using this code:

var spinner1 = FindViewById<Spinner>(Resource.Id.planets_spinner);
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem);
spinner1.Adapter = adapter;

SqlConnection con = new SqlConnection(@"Data Source=192.168.1.101;Initial Catalog=RK1;user id=admin;password=1234");
con.Open();

SqlCommand sqlCmd = new SqlCommand("SELECT * FROM InventoryMainGroupItems where TaxOmada=0", con);

SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
adapter.Add("MainGroupItemName");

}
sqlReader.Close();


enter image description here

Answer

You need to use an SpinnerAdapter and assign it to your Spinner.

i.e. using an ArrayAdapter:

var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem);
adapter.Add("First");
adapter.Add("Second");
var spinner1 = FindViewById<Spinner>(Resource.Id.planets_spinner);
spinner1.Adapter = adapter;

SQL.Net Example:

string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "myAppData.db3");
var db = new SQLiteConnection(dbPath);
db.CreateTable<Category>();

if (db.Table<Category>().Count() == 0)
{
    db.Insert(new Category()
    {
        Description = "First"
    });
    db.Insert(new Category()
    {
        Description = "Second"
    });
}

var categories = db.Table<Category>();
var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem);
foreach (var category in categories)
{
    adapter.Add(category.Description);
}
var spinner1 = FindViewById<Spinner>(Resource.Id.planets_spinner);
spinner1.Adapter = adapter;