Daniel
Daniel

Reputation: 5

How can I generate a different image in a Visual Studio picturebox depending on a listbox?

In Visual Studio, in one of the window forms, I've got a ListBox that is retrieving it'information from a data table in SQL Server. For this data table the primary key is called ID. In the same window form I've added a picturebox, where I would like the images to be generated depending on the selection in the listbox. The images are saved in a folder on the project folder.

I'm already using a method to populate the listbox so maybe I can use that to determine which image needs to be displayed:

 static SqlCommand com = new SqlCommand("SELECT *,CONCAT(name,' ',year) as date_bikes FROM model", conn);

 SqlDataAdapter adaptb = new SqlDataAdapter(com);

 DataTable bikeT = new DataTable();

void Method1() --this method fills the checkedlistbox

 {

 adaptb.Fill(bikeT);

 bikes.Items.Clear();

 bikes.DataSource = bikeT;

 bikes.ValueMember = "ID";

 bikes.DisplayMember = "namemod";

 }

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

    {
        foreach (object itemChecked in listBox1.Items)
        {
            DataRowView castedItem = itemChecked as DataRowView;
            string name = castedItem["namemod"].ToString();
        }
      if (name == "Bike 1")
        {
          pictureBox1.Image = Image.FromFlie("file path")
        }
      else if (name == "Bike 2")
        {
          pictureBox1.Image = Image.FromFlie("file path")
        }
    and so on...

Upvotes: 0

Views: 148

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

You need to take the SelectedItem instead of looping through the array:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataRowView castedItem = listBox1.SelectedItem as DataRowView;
    string name = castedItem["namemod"].ToString();

    if (name == "Bike 1")
    {
      pictureBox1.Image = Image.FromFlie("file path")
    }
    else if (name == "Bike 2")
    {
      pictureBox1.Image = Image.FromFlie("file path")
    }
and so on...

Upvotes: 0

Related Questions