简体   繁体   中英

display item with multiple values from listbox into textbox using access database

I am trying to display item values in their respective textbox when an item is selected in the listbox

this is how I have it set up:

  1. This is how the values are shown to the list box

      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. This is how i'm trying to make the values from the listbox show to a textbox

      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 is the listbox and EditIDTB.Text = reader["ID"].ToString(); is me trying to show the value in one of the textboxes.

Right now, when I click on an item nothing shows in the text boxes. Any help appreciated

There are better ways to accomplish what you're doing, so you can take advantage of DisplayMember and ValueMember , but the problem you're having stems from using the entire Text field that you're displaying to the user.

If their selection looked like this:

001     Acme  Anvil  Weapon  10.00

Then your query ends up being:

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

Just split the part off you're interested in:

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

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

To get around issues with item names that have multiple spaces, you might want to select based on the ID instead:

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

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

You might also want to check into parameterizing your queries, but that's a different issue...

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