Modifying a column in DGV to be a Combobox Bound to DataBase

不想你离开。 提交于 2019-12-13 04:23:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!