问题
I created a view named "FamilyView" to join 2 tables(Families and SStatus) and replace an id in the first table(Families) by its name existing in the second table(SStatus) (the column is now called "Status")
This view is now displayed in a datagridview that the user can modify
Sda = new SqlDataAdapter("Select * from FamilyView",con);
Sda.Fill(ds);
dg.DataSource = ds.Tables[0];
dg.Refresh();
What i want is to transform the column cells "Status" to comboboxes containing all Names from SStatus
SqlDataAdapter sadapter = new SqlDataAdapter("Select * From SStatus", con);
DataSet ds1 = new DataSet();
sadapter.Fill(ds1);
i found this code:
DataGridViewComboBoxCell ComboColumn = (DataGridViewComboBoxCell)(dg.Rows[i].Cells[0]);
ComboColumn.DataSource = ds1.Tables[0];
ComboColumn.DisplayMember = "Name";
but i can't replace the cell
and this code but I'm not sure how to use it:
Adding bound combobox to datagridview
BindingSource StatusBD = new BindingSource();
StatusBD.DataSource = ds1;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Status";
colType.DropDownWidth = 90;
colType.Width = 90;
//colType.DataPropertyName = "Name";
colType.DataSource = ds;
colType.DisplayMember = "Name";
colType.ValueMember = "IdStatus";
dg.Columns.Insert(dg.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
回答1:
Your data source is empty: it should contain 2 tables: one with the SStatus and one with Families.
and then follow my as in your post:
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
BindingSource wizardBindingSource = new BindingSource();
wizardBindingSource.DataSource = dataSet;
wizardBindingSource.DataMember = "protocol"; // This is the table in the set
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = wizardBindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols"
Here idProtocol (which is referenced as protocol in the "pcap" table) is mapped to protocolName.
来源:https://stackoverflow.com/questions/16758407/modifying-a-column-in-dgv-to-be-a-combobox-bound-to-database