简体   繁体   中英

How to show array elements on listbox selecteditem ? c# winforms

i would like to get array elements on listbox selectedindex. Also it shows what excatly found array elements but it doesnt select first element of array on listbox

Listbox = cbx_dekor_paneli

    string[] dekordizisi;
    void listedendekoral()
    {
        dekordizisi = Sipariş_Listesi_Güncelle.dekorgonder.ToString().Split(',');

        for (int i = 0; i < dekordizisi.Count(); i++)
        {
            cbx_dekor_paneli.SelectedIndex = 
            cbx_dekor_paneli.FindString(dekordizisi[i].ToString());

            //already tried that one
            //cbx_dekor_paneli.SelectedItem = dekordizisi[i].ToString();
        }

    }

Listbox items add from mysql

        void DB_dekor()
    {
        db.vtbaslat();
        vtbaglan();
        try
        {
            cbx_dekor_paneli.Items.Clear();
            //dekorlar
            MySqlCommand listegor = new MySqlCommand("select * from dekor order by dekor_id asc", db.baglanti);
            MySqlDataReader liste = listegor.ExecuteReader();
            while (liste.Read())
            {
                cbx_dekor_paneli.Items.Add(liste["dekor_kod"].ToString());
            }
            liste.Close();
            listegor.Dispose();
        }
        catch (Exception hata)
        {
            MessageBox.Show(hata.Message);
        }
    }

Update

I made a mistake on my database. some values had spaces. Also i prefer to Selection Mode: MultiSimple Solve with that code

        cbx_dekor_paneli.ClearSelected();
        dekordizisi = Sipariş_Listesi_Güncelle.dekorgonder.ToString().Split(',');

        for (int i = 0; i < dekordizisi.Count(); i++)
        {
            cbx_dekor_paneli.SelectedIndex = cbx_dekor_paneli.FindStringExact(dekordizisi[i].ToString());
        }

If you're trying to select multiple items on the ListBox based on the content of the array:

for (int i = 0; i < dekordizisi.Count(); i++)
    {
        cbx_dekor_paneli.SetSelected(cbx_dekor_paneli.FindString(dekordizisi[i]), true);
    }

Also make sure the ListBox.SelectionMode Property is set to MultiExtended

May this helps you with your code.

string dekordizisi = [];
foreach(int i in dekordizisi.GetSelectedIndices())
{
  dekordizisi = dekordizisi + dekordizisi.Items[i] + ",";
}
dekordizisi = dekordizisi.Remove(dekordizisi.Length - 1);

in this code we are initializing a variable "dekordizisi" to an array and then with foreach we are adding it inside the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM