繁体   English   中英

在C#winforms中处理datagridview中的组合框

[英]handling combobox in datagridview in C# winforms

嗨,我有一个窗口格式的数据网格,名为“ dataGridView1”,并且在dataGridView1中有组合框; 我正在从数据库中显示组合框中的数据,并且在加载窗口时会在该组合框中加载所有数据。 我为此功能LoadModels。 我要显示一列ModelName,在valuemember中将有MedelID,所以我希望当用户从组合框中选择任何模型时,它会给我该模型的ID,称为“ ModelID”。

public frmBikeOrder()
{
    InitializeComponent();
    StartPosition = FormStartPosition.CenterScreen;
    FormBorderStyle = FormBorderStyle.FixedSingle;
    ControlBox = false;
    LoadModels();
}

private void LoadModels()
{
    RST_DBDataContext conn = new RST_DBDataContext();
    List<TblBikeModel> AllModels = (from s in conn.TblBikeModels
                     select s).ToList();
    Column2.DataSource = AllModels;
    Column2.DisplayMember = "ModelName";
    Column2.ValueMember = "ModelID";
}

值更改时我有一个函数,组合框值更改后我想在消息框中输入值

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
       {
            ComboBox cmb =  ComboBox();
            MessageBox.Show(cmb.SelectedValue.ToString());
       }
}

用这个

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
       {
            bool val = (bool)dataGridView1.SelectedCells[0].Value;
            MessageBox.Show(val.ToString());
       }
}

您将使用dataGridView1.SelectedCells[0]获得选定的单元格,并且其值(已选中)的值为Property。

您还可以使用DataGridViewCellEventArgs并执行以下操作:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
       {
            bool val = (bool)dataGridView1[e.ColumnIndex, e.RowIndex].Value;
            MessageBox.Show(val.ToString());
       }
}

将组合框的属性设置为:

        ModelComboBox.SelectedValuePath = "ModelID";
        ModelComboBox.DisplayMemberPath = "ModelName";

然后,ModelComboBox.SelectedValue将为ModelID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM