Hi Paul,
You can use DataTable.DefaultView.RowFilter to do the filter job. But before you do the filter, you need to make a copy of the DataTable, that enable each cell has its own DataSource. If all the cells share the same DataTable as DataSource, you will meet error when filtering. Here is a simple example. Hope it give you some light to do with this case.
public partial class Form1 : Form
{
private DataTable dtComboBox = new DataTable();
public Form1()
{
InitializeComponent();
dtComboBox.Columns.Add("ID", typeof(int));
dtComboBox.Columns.Add("Name", typeof(string));
dtComboBox.Rows.Add(0, "Item0");
dtComboBox.Rows.Add(1, "Item1");
dtComboBox.Rows.Add(2, "Item2");
dtComboBox.Rows.Add(3, "Item3");
dtComboBox.Rows.Add(4, "Item4");
DataGridViewComboBoxColumn dgvCmb = new DataGridViewComboBoxColumn();
dgvCmb.DataSource = dtComboBox;
dgvCmb.DisplayMember = "Name";
dgvCmb.ValueMember = "ID";
dataGridView1.Columns.Add(dgvCmb);
dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
}
void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cmb = e.Control as ComboBox;
if (cmb != null)
{
DataTable dt = dtComboBox.Copy();
dt.DefaultView.RowFilter = "Name='Item" + dataGridView1.CurrentCell.RowIndex.ToString() + "'";
cmb.DataSource = dt.DefaultView; }
}
}
In this sample, first I set the DataSource property of DataGridViewComboBoxColumn with the dtComboBox. Then I handle the DataGridView.EditingControlShowing event to get the ComboBox from the cell. Therefore I can do the copy and filter the rows for the copied one and bind it to the ComboBox. In my example, only the item whose index is the same as the current editing cell’s RowIndex will be shown in the drop down list.
If you have any doubt, please feel free to tell me.
Sincerely,
Kira Qian
Send us any feedback you have about the help from MSFT at EMAIL REMOVED
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the
All-In-One Code Framework!