Nox Eternal
Nox Eternal

Reputation: 15

Item in ListBox can have different value in textbox?

I have this ListBox that displays items I dragged from my DataGridView. Items in ListBox displays their MenuCode. What I want to happen is I want to show the MenuPrice of each item I have on ListBox on a TextBox. I tried to do this but the MenuCode displays on that TextBox. Please see the image below.

enter image description here

Is it possible to have the MenuPrice displayed on that TextBox? I have done this code but I dont think this is right.

private void menuDataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) //this code triggers when I dragged an item from datagridview to listbox.
{
    menuDataGrid.DoDragDrop(menuDataGrid.CurrentRow.Cells[3].Value.ToString(), DragDropEffects.Copy);
}

private void menuListBox_SelectedValueChanged(object sender, EventArgs e) //this is the code when I select an item on the listview, then appears at the textbox
{        
    pricetxtbox.Text = menuListBox.SelectedItem.ToString();
}

private void ShowDataToGrid()  //datagrid code
{
    db_connection();

    MySqlDataAdapter datagrid = new MySqlDataAdapter();
    string selectAll = "SELECT * FROM Menu";
    datagrid.SelectCommand = new MySqlCommand(selectAll, connect);

    DataTable tbl = new DataTable();
    datagrid.Fill(tbl);

    BindingSource bs = new BindingSource();
    bs.DataSource = tbl;

    menuDataGrid.DataSource = bs;
    menuDataGrid.Columns[6].Visible = false;
    menuDataGrid.Columns[7].Visible = false;
}

Upvotes: 0

Views: 76

Answers (2)

Mohamed Najiullah
Mohamed Najiullah

Reputation: 423

I'm going to assume that the MenuPrice is also present on the GridView at a different cell, say Cells[4].

Then you can do something like this

private void menuListBox_SelectedValueChanged(object sender, EventArgs e) //this is the code when I select an item on the listview, then appears at the textbox
{        
    foreach (DataGridViewRow row in menuDataGrid.Rows)
    {
        if (row.Cells[3].Value.ToString().Equals(menuListBox.SelectedItem.ToString()))
        {
            pricetxtbox.Text = row.Cells[4].Value.ToString();
            break;
        }
    }
}

Upvotes: 1

user7861944
user7861944

Reputation:

You should pack your data into an object class with properties you want to display and hold. For example:

public class MenuItem()
{
    public float MenuPrice { get; set; }
    public string MenuCode { get; set; }
}

If you store data of type MenuItem in your ListView, you will be able to do:

private void menuListBox_SelectedValueChanged(object sender, EventArgs e) textbox
{        
    var item = menu.ListBoxItem.SelectedItem as MenuItem;
    if(item == null) return;

    pricetxtbox.Text = item.MenuPrice;
}

This would be one way to do it, if you want to enhance your code you should probably consider using databinding for you textboxes.

Upvotes: 1

Related Questions