【问题标题】:handling combobox in datagridview in C# winforms在 C# winforms 中处理 datagridview 中的组合框
【发布时间】:2013-09-16 06:30:11
【问题描述】:

您好,我有一个名为“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());
       }
}

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    使用这个

    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] 获取选定的单元格,它的值(已检查)与值属性。

    您也可以使用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());
           }
    }
    

    【讨论】:

    • 非常感谢它帮助了我
    【解决方案2】:

    设置组合框的属性为:

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

    那么 ModelComboBox.SelectedValue 将是 ModelID。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多