【问题标题】:How can I generate a different image in a Visual Studio picturebox depending on a listbox?如何根据列表框在 Visual Studio 图片框中生成不同的图像?
【发布时间】:2018-01-23 08:08:57
【问题描述】:

在 Visual Studio 中,在一个窗口窗体中,我有一个 ListBox,它从 SQL Server 的数据表中检索它的信息。对于这个数据表,主键称为ID。在同一个窗口窗体中,我添加了一个图片框,我希望根据列表框中的选择生成图像。图像保存在项目文件夹的文件夹中。

我已经在使用一种方法来填充listbox,所以也许我可以使用它来确定需要显示哪个图像:

 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...

【问题讨论】:

  • 使用简单的 IF 和检查更改事件确定检查哪个项目,然后将 picturebox.Image 属性设置为图片的路径?
  • 您能详细说明一下吗? '检查更改事件确定检查哪个项目'是什么意思?
  • 首先,您必须设置 CheckedListBox1.SelectionMode = SelectionMode.One; ,这意味着只能检查选中列表框中的单个项目,然后检查此问题 stackoverflow.com/questions/4875540/… 的答案,使用 for loop 会得到你选中的单个项目并使用if 为图片框设置适当的图片,所有这些都将在checkedlistbox 控件的事件ItemCheck
  • @Veljko89 我决定使用 ListBox 而不是 CheckedListBox。您能否提供一个示例,说明如何最好地实现这一点,以便我生成图像。
  • 原理一样,通过ListBox.Items读写,有if (item == checked)选择正确图片的url

标签: c#


【解决方案1】:

您需要使用SelectedItem 而不是循环遍历数组:

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...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 2018-07-18
    • 1970-01-01
    相关资源
    最近更新 更多