C#为datagridview中的组合框设置数据源

本文关键字:设置 数据源 组合 datagridview | 更新日期: 2023-09-27 18:23:35

我在一个旧程序中有两个表,单位和频率。频率表有一个外键到单位表,一个数据网格视图设置它的数据源到单位表。我想添加一个组合框到这个数据网格视图包含频率。

选择单位

var data = context.Units.Where(u => u.Center.center_name.Trim() == cmbCenters.Text.Trim()).ToList();
// my datagridview
dgResult.AutoGenerateColumns = false;
dgResult.Columns.Clear();
....
....
if (chkRx.Checked)
{
    DataGridViewComboBoxColumn rxColumn = new DataGridViewComboBoxColumn();
    rxColumn.Name = "RX";
    rxColumn.ValueMember = "unitID";
    rxColumn.DispalyMember = "rxfreq";
    rxColumn.Datasource = context.Frequencies.ToList();
    dgResult.Columns.Add(rxColumn);
}
if (chkTx.Checked)
{
    DataGridViewComboBoxColumn txColumn = new DataGridViewComboBoxColumn();
    txColumn.Name = "TX";
    txColumn.ValueMember = "unitID";
    txColumn.DispalyMember = "txfreq";
    txColumn.Datasource = context.Frequencies.ToList();
    dgResult.Columns.Add(txColumn);
}
dgResult.DataSource = data;

更新:

我更改了代码,但所有频率都显示在组合框中,而不仅仅是每行中该单元ID的频率。

C#为datagridview中的组合框设置数据源

if (chkRx.Checked)`
{
    DataGridViewComboBoxColumn rxColumn = new DataGridViewComboBoxColumn();
    rxColumn.Name = "RX";
    //rxColumn.DataPropertyName = "BRxs";
    var datafrequencies =context.Frequencies.ToList();
    rxColumn.DataSource = datafrequencies;
    rxColumn.ValueMember = "frequencyId";
    rxColumn.DisplayMember = "frequencyName";
    dgResult.Columns.Add(rxColumn);
}
dgResult.DataSource = data;`

在行中搜索频率的每个数据

  private void dgResult_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
      {
        DataGridViewComboBoxEditingControl comboControl = e.Control as DataGridViewComboBoxEditingControl;
        if (comboControl != null)
        {
            //Set the DropDown style to get an editable ComboBox
            if (comboControl.DropDownStyle != ComboBoxStyle.DropDown)
            {
                comboControl.DropDownStyle = ComboBoxStyle.DropDown;
                //int r = dgvconn.CurrentRow.Index;
            }
        }
    }