【问题标题】:display item with multiple values from listbox into textbox using access database使用访问数据库将具有多个值的项目从列表框中显示到文本框中
【发布时间】:2019-02-07 15:32:40
【问题描述】:

当在列表框中选择项目时,我试图在其各自的文本框中显示项目值

我是这样设置的:

  1. 这是在列表框中显示值的方式

            command.CommandText = "select * from ItemsList";
            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                EditItemBrowserBox.Items.Add(reader["ID"].ToString() + "         " + reader["ItemBrand"].ToString() + "  " + reader["ItemName"].ToString() + "  " + reader["ItemType"].ToString() + "  " + reader["ItemPrice"].ToString());   
            }
    
  2. 这就是我试图将列表框中的值显示到文本框的方式

            command.CommandText = "select * from ItemsList where ItemName='" + EditItemBrowserBox.Text + "' ";
            OleDbDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                EditIDTB.Text = reader["ID"].ToString();
                ItemNameAddTB.Text = reader["ItemName"].ToString();
                ItemTypeAddTB.Text = reader["ItemType"].ToString();
                ItemBrandAddTB.Text = reader["ItemBrand"].ToString();
                ItemPriceAddTB.Text = reader["ItemPrice"].ToString();
            }
    

EditItemBrowserBox 是列表框,EditIDTB.Text = reader["ID"].ToString();是我试图在其中一个文本框中显示值。

现在,当我单击一个项目时,文本框中没有显示任何内容。任何帮助表示赞赏

【问题讨论】:

  • 那么我怎样才能让它在字符串中查找值?

标签: c# ms-access


【解决方案1】:

有更好的方法来完成您正在做的事情,因此您可以利用 DisplayMemberValueMember,但您遇到的问题源于使用您正在显示的整个 Text 字段给用户。

如果他们的选择是这样的:

001     Acme  Anvil  Weapon  10.00

那么你的查询最终是:

select * from ItemsList where ItemName='001     Acme  Anvil  Weapon  10.00'

只需将您感兴趣的部分分开即可:

var itemName =
    EditItemBrowserBox.Text.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)[2];

command.CommandText = $"select * from ItemsList where ItemName='{itemName}'";

要解决项目名称包含多个空格的问题,您可能希望改为基于 ID 进行选择:

var id = EditItemBrowserBox.Text.Split(' ')[0];

command.CommandText = $"select * from ItemsList where ID='{id}'";

您可能还想检查参数化查询,但这是一个不同的问题...

【讨论】:

  • 非常感谢,但它只在ItemName是一个单词时才起作用,但当项目名称中有2个单词时它不起作用,我确保在有时拆分仅 2 个空格
  • 我会调查一下,谢谢,我希望我能投票给你
  • 只是为了让人们可以看到:为了能够使用空格,您可以按 ID 而非 itemname 排序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 2020-03-13
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多