简体   繁体   中英

Get present primary keys from link table, set Checkstate checklistbox

I have a CheckedListbox which contains values from some table called products. The idea is to check the products that are associated to a customer. Now it does save correctly in an link table, yet when loading it again, the items that were checked do not get loaded correctly into the CheckedListbox.

So from that link table where, I would like to get all rows from just one column. All tables are already loaded into the application so I don't want to use sql.

I've tried using linq, with no success, Ids is just empty here.

int[] Ids = (from m in dataset.Tables["LinkTable"].AsEnumerable()
                where m.Field<int>("customerId") == customerId
                select m.Field<int>("productId")).ToArray();

Then, if I do succeed to get those Id's, I would like to get the indexes of those primary keys so I can set the correct products to checked . I've tired doing it like this, but this gives me error in other parts of the program, because I am setting a Primary key to a global datatable. Datagridviews don't like that.

        DataColumn[] keyColumns = new DataColumn[1]; 
        keyColumns[0] = dataset.Tables["products"].Columns["Id"];
        currentPatient.GetTheDataSet.Tables["products"].PrimaryKey = keyColumns;

        foreach (int Id in Ids)
        {
            DataRow row = dataset.Tables["Products"].Rows.Find(Id);
            int index = dataset.Tables["Products"].Rows.IndexOf(row);
            clbMedications.SetItemChecked(index, true);

        }

I would like to do that last part without specifying a primary key, I couldn't find how to do that in linq.

I know it consists of 2 questions, but perhaps this can be done with just one linq statement so I better combine them.

[EDIT]

Finally, i think i've got what you need:

var qry = (from p in ds.Tables["products"].AsEnumerable()
    select new {
        Id = p.Field<int>("Id"),
        Index = ds.Tables["products"].Rows.IndexOf(p),
        Checked = ds.Tables["LinkTable"].AsEnumerable().Any(x=>x.Field<int>("productId") == p.Field<int>("Id") && x.Field<int>("customerId")==customerid)
    }).ToList();

Above query returns the list, which you can bnid with CheckedListbox .

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