简体   繁体   中英

handling combobox in datagridview in C# winforms

Hi i have a datagrid in window form called "dataGridView1" and i have combobox in the dataGridView1; i am displaying the data in combobox from database and all data loads in that combobox when window loads. i have function LoadModels for that. there is one column ModelName which i want to display and in valuemember there will be MedelID, so i want when user select any model from combobox then it give me id of that model called "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";
}

i have a function when value changes, i want the value in messagebox after combobox value change

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

use this

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

you get the selected cell using dataGridView1.SelectedCells[0] and it's value(is checked) with the value Property.

you can also use the DataGridViewCellEventArgs and do:

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());
       }
}

Set the property of combobox as:

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

Then ModelComboBox.SelectedValue will be ModelID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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