4

I have a DataGridView that I am binding to a POCO. I have the databinding working fine. However, I have added a combobox column that I want to be different for each row. Specifically, I have a grid of purchased items, some of which have sizes (like Adult XL, Adult L) and other items are not sized (like Car Magnet.)

So essentially what I want to change is the DATA SOURCE for a combobox column in the data grid. Can that be done?

What event can I hook into that would allow me to change properties of certain columns FOR EACH ROW? An acceptable alternative is to change a property when the user clicks or tabs into the row. What event is that?

Seth

EDIT
I need more help with this question. With Triduses help I am SO close but I need a bit more information.

First, per the question, is the CellFormatting event really the best/only event for changing the DataSource for a combo box column. I ask because I am doing something rather resource/data intensive, not merely formatting the cell.

Second, the cellformatting event is being called just by having the mouse hover over the cell. I tried to set the FormattingApplied property inside my if-block and then I check for it in the if- test but that is returning a weird error message. My ideal situation is that I would apply change the data source for the combo box once for each row and then be done with it.

Finally, in order to set the data source of the combobox colunm I have to be able to cast the Cell inside my if block to a type of DataGridViewComboBoxColumn so that I can fill it with rows or set the datasource or something. Here is the code I have right now.

Private Sub ProductsDataGrid_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles ProductsDataGrid.CellFormatting

    If e.ColumnIndex = ProductsDataGrid.Columns("SizeDGColumn").Index Then ' AndAlso Not e.FormattingApplied Then
        Dim product As LeagueOrderProductInfo = DirectCast(ProductsDataGrid.Rows(e.RowIndex).DataBoundItem, LeagueOrderProductInfo)
        Dim sizes As LeagueOrderProductSizeList = product.ProductSizes
        sizes.RemoveSizeFromList(_parentOrderDetail.SizeID)

        'WHAT DO I DO HERE TO FILL THE COMBOBOX COLUMN WITH THE sizes collection.

    End If

End Sub

Please help. I am completely stuck and this task item should have taken an hour and I am 4+ hours in now. BTW, I am also open to resolving this by taking a completely different direction with it (as long as I can be done quickly.)

Seth

5 Answers 5

3

There isn't one, unfortunately. What you're going to have to use is the CellFormatting event.

That will fire for every cell, but you can figure out if you're in the right column by checking the column index of the cell, and you can then do your logic if you're in the column you want to work with.

If you decide you want to change it when they select a row instead of when it's displayed, you can use RowEnter instead.

Here's a code example of how to use this event. This one sets the column to have an image in it.

 Private Sub dgActiveOccurrences_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgActiveOccurrences.CellFormatting
        If e.ColumnIndex = dgActiveOccurrences.Columns("colActiveUnreadFlag").Index Then
            Dim occ As Occurrence = DirectCast(dgActiveOccurrences.Rows(e.RowIndex).DataBoundItem, Occurrence)
            If occ.LastReadBy <> OccurrenceSession.Self.UserManager.MyStaffRecord.StaffId Then
                e.Value = My.Resources.Icon_UnreadFlag
            End If
        End If
End Sub
2
  • Is it possible you could do a code snippet. Specifically I suppose I have to cast sender to something and then get the column index. Correct? Jan 27, 2011 at 21:50
  • Or it looks like I use the event args. It has a column index. Jan 27, 2011 at 21:56
2

I didn't go the way of catching an event to change displayed values in a combobox for each row...Take a look at this approach (example), it's very straightforward and easy to implement and does exactly what you want imho.:

  1. Declare an Item class with two simple properties (Name, Type)

  2. Create a DataGridView with two columns (one for Name, and the second for Type with ColumnType = DataGridViewComboBoxColumn and dataPropertyName = Type)

  3. "Attach" your (I assume) list of poco's to the DataGridView

  4. And afterwards loop one-time only through your collection of rows; grab the DataGridViewComboBoxColumn for that row; Change it's items property based upon the criteria that you have for the poco in that row.

I leave it up to you to grab the poco for a specific row, or alternatively read some properties from hard-coded columns in the row...

Here's some sample code:

namespace DataGridViewCustomComboboxItemsPerRow
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            List<int> types = new List<int>();
            List<Item> items = new List<Item>();
            Item item;
            for (int i = 0; i < 100; i++)
            {
                item = new Item();
                item.Name = "Item" + i.ToString();
                item.Type = i;

                items.Add(item);
                types.Add(i);
            }

            //typeDataGridViewComboBoxColumn.DataSource = types;
            itemBindingSource.DataSource = items;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            DataGridViewComboBoxCell dgvc;

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dgvc = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[1];

                // Your CUSTOM code here, I just did some stupid thing here...
                dgvc.Items.Add(i - 1);
                dgvc.Items.Add(i);
                dgvc.Items.Add(i + 1);
            }
        }
    }

    public class Item
    {
        private string _name;
        private int _type;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public int Type
        {
            get { return _type; }
            set { _type = value; }
        }
    }
}

The code is in C# but is pretty basic, so I guess it won't cause problems in VB.NET. And this code really makes a one time loop (O(n)) to configure your combo's for different rows and than it's done.

Hope this helps. Joep.

2
0

I am not sure if this is feasible for you. Can you try the same in the dataGridView1_DataBindingComplete event

foreach (DataGridViewRow var in dataGridView1.Rows)
{
      if (var.Cells[0] is DataGridViewComboBoxCell)
      {
          (var.Cells[0] as DataGridViewComboBoxCell).Items.Add("first col values");
      }
      if (var.Cells[1] is DataGridViewComboBoxCell)
      {
          (var.Cells[1] as DataGridViewComboBoxCell).Items.Add("second col values");
      }
}
0

If you can not add a row to this grid u can use the event DataBindingComplete and this event is fired when the grid finish the binding of it data and if you can add rows you have to use in addition the event NewRowNeeded this event is fired wen u click an the new row at the bottom of the grid and you will not worry about filling the same combo multiple time

0

You can do this with the CellBeginEdit event. Handle the event, check if the column being edited is your DataGridViewComboBox column and change the items in the combobox.

This may not work if you are binding a data source to the combobox. I have only tried it manually adding a list of items:

void grid_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    if (grid.Columns[e.ColumnIndex].Name == "MyComboColumn")
    {
        // get the value of a different cell in this row that will be used to determine which values are in the combobox
        string other_value = grid[0, e.RowIndex].Value.ToString();

        // get the combobox cell being edited
        DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)grid[e.ColumnIndex, e.RowIndex];

        // update the list of items in the combobox
        cell.Items.Clear();
        if (other_value == "something")
            cell.Items.AddRange(new object[] { "Value1", "Value2" });
        else
            cell.Items.AddRange(new object[] { "Value3", "Value4" });

    }
}

Note: this code is untested, I'm not at my development machine at the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.