简体   繁体   中英

Delete row from datatable based on condition

In my DataGrid I used a ComboBox in the first column, so it will fetch some data from the database using the DisplayMember and ValueMember concepts. Now I want to remove the value from the ComboBox which is previously selected.

Populating the ComboBox code is given below:

   dTable = getDummyTable.GetDummyTble("Dummy", "DNO", "All");
   dCmbData = dTable;
   cmbDeno.DataSource = dTable;
   cmbDeno.DisplayMember = "dyName";
   cmbDeno.ValueMember = "dyRemarks";

The next row of selection there should not be a duplicate value in the ComboBox.

How can I achieve this?

Can anyone help me with this?

well try this one out. You have the DataTable which you are using to bind all combos (correct me if I'm wrong). Now all we need to do is that when an item is selected from any combo, we need to remove that item from all the other combos). You will need to declare a class level dictionary to store which combo had what value stored previously:

IDictionary<ComboBox, DataRow> _prevSelection;

//Please don't mind if syntax is wrong worked too long in web
comboBox.OnSelectedIndexChanged += fixItems;

private void fixItems(object sender, EventArgs e)
{
    var cbo= sender as ComboBox;
    if(cbo==null) return;

    var prev = _prevSelection[cbo];

    var row=<GET ROW FROM DATATABLE FOR CURRENT SELECTED VALUE>;

    _prevSelection[cbo] = row;

    UpdateOtherCombos(cbo, prev, cbo.SelectedItem.Value);
}

private void UpdateOtherCombos(ComboBox cbo, DataRow prev, object toRemove)
{
    foreach(var gridrow in <YourGrid>.Rows)
    {
        var c = <FIND COMBO IN ROW>;
        if(cbo.Id == c.Id) continue;//combo that triggered this all
        var itemToRemove=null;
        foreach(var item in c.Items)
        {
            if(item.Value == toRemove)
            {
                itemToRemove = item;
                break;
            }
        }

        //or you can get index of item and remove using index
        c.Items.Remove(itemToRemove);

        //Now add the item that was previously selected in this combo (that 
        //triggered this all)
        c.Items.Add(new ComboBoxItem{Value = prev["ValueColumn"], 
                                        Text = prev ["TextColumn"]});
    }
}

This is just to give you an idea that may help you to find an optimal solution rather than iterating over all combos as it will slow down if you have too many rows in grid or too many items in combos. Still even with this you need to put up some functions/code to make it working. Also please note that I have not worked on WinForms for some time and you need to check if things like ComboBoxItem etc. and any functions called on them exist. :)

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