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

时间:2015-11-20 16:58:31

标签: c# linq datagridview combobox

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

选择单位

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;

更新:

我改变了我的代码,但所有频率在组合框中显示的不仅仅是每行中这个unitID的频率。

1 个答案:

答案 0 :(得分:0)

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;

            }
        }
    }