简体   繁体   中英

DataGridView Winforms Populate ComboBoxCell

I am making one software where the user will create an invoice using datagridview. I have some textbox cells and some combobox cells. There are some things I want to do:

  1. I want to fill the combobox cells from database table. I tried this:

    DataTable tblItems = UtilityClass.GetDataTable("SELECT ItemName,ItemID FROM Items"); DataGridViewComboBoxColumn itemCol=DataGridViewComboBoxColumn)dataGridViewNewBill.Columns["ColItem"]; itemCol.DataSource = tblItems; itemCol.DisplayMember = "ItemName"; itemCol.ValueMember = "ItemID";

    But, after an item is selected, and when the focus is moved to a different cell, the item selected in the combobox (or text of textbox) cell disappears.
    EDIT : It seems as if selecting an item in the combobox causes all the combobox cells to get that value because they have the same datasource, But even if it's the case. why the combox/textbox cell loses it's value after focus is moved to a different cell.

Are you handling any specific events which is erasing the data.

Selecting a value causes it to be selected for other cells because the Grid uses a common ComboBox across all cells of the combobox column which is the EditingControl for enabling selection of the values of the column.

You can control the behviour by handling the EditingControlShowing event

Try setting this mode

dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;

Well, I am now quite sure that when we use the same data source for 2 or more comboboxes, changing the value for one causes the others to change also.

What I did was disable adding new rows and

  1. In the form load added one row, setting the datasource of that particular combobox cell(not column).
  2. When the user moves to the last cell and presses enter key, I create another row and do the same as above.

In this way each cell has a different data source, although I have to do some more work but it worked.

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