0

I am new to windows forms application development.

I am using an editable grid view for data entry.

One of the fields in the grid view is of type ComboBoxColumn. I am filling the data in code.

My problem is if data item count is greater than 0 then first item should be selected automatically.

My code from Page_Load() is:

private void Form1_Load(object sender, EventArgs e)
{
    cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Study\sem 6\Practice\WindowsFormsApplication1\Practice.accdb");
    cn.Open();
    cmd = new OleDbCommand("Select * from Grade", cn);
    da = new OleDbDataAdapter(cmd);
    ds = new DataSet();
    da.Fill(ds);
    cn.Close();
}

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    DataGridViewComboBoxCell cmb = (DataGridViewComboBoxCell)(dataGridView1.Rows[e.RowIndex].Cells[1]);
    cmb.DataSource = ds.Tables[0];
    cmb.DisplayMember = "Grd";
    cmb.ValueMember = "ID";

    if(cmb.Items.Count > 0)
    // Here I am not finding the the combo box's SelectedIndex Property.
}

Please help to solve this problem.

Thanks in advance.

fhnaseer
  • 7,159
  • 16
  • 60
  • 112
Mohemmad K
  • 809
  • 7
  • 33
  • 74

1 Answers1

0

The class DataGridViewComboBoxCell does not have those properties. Look in the documentaion

Others have tried a different approach. In you code it would look somethink like this:

    private ComboBox _chashedComboBox;

    private void dataGridView1_EditingControlShowing()
    {
       _chashedComboBox = e.Control as ComboBox;
    }

    private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
            var cmb = _chashedComboBox;
            if(cmb != null)
            {
              cmb.DataSource = ds.Tables[0];
              cmb.DisplayMember = "Grd";
              cmb.ValueMember = "ID";

              if(cmb.Items.Count > 0) 
                cmb.SelectedIndex = 0;
             }
    }
Jens Kloster
  • 11,099
  • 5
  • 40
  • 54
  • Sir, I tried as per your answer but getting error in `dataGridView1_EditingControlShowing()` that Unable to cast object of type `DataGridViewTextBoxEditingControl` to type `ComboBox` – Mohemmad K Apr 04 '13 at 13:27
  • aah yeah - sry, my cast was wrong. not every cell contains a combobox. Now it will just return null instead of throwing an error. try it. – Jens Kloster Apr 04 '13 at 13:30
  • Sir, I tried your updated answer, programs gives no error but the records are not fetched from the data set. I debugged the program and it shows that control does not go in `dataGridView1_CellBeginEdit()` @JensKloster – Mohemmad K Apr 05 '13 at 05:36