开发者

Filter Combobox Items Based on Values in a 2nd Column

开发者 https://www.devze.com 2023-02-08 15:28 出处:网络
I have a Datatable(invTable) with 19 columns in it 开发者_如何学运维that I created from a csv file. From that Datatable I\'m using the values in column2(name) to populate a Combobox.

I have a Datatable(invTable) with 19 columns in it 开发者_如何学运维that I created from a csv file. From that Datatable I'm using the values in column2(name) to populate a Combobox.

What I need to do is filter the items from column2(name) that show up in the Combobox only if the value in column9(type) matches a preset value. i.e. only if the value in column9(type) is 15.

I also need to be able to work with the values in the rest of the columns based on the selected item in the Combobox. Assigning them to variables such as SelectedCol1-SelectedCol19 so that they can be used in other calculations throughout the program.

EDIT: I was able to find something that suited my needs with the following code.

var query = invTable.AsEnumerable().Where(c => c.Field<String>("Type").Equals("15"));
combo1.DataSource = query.AsDataView();
combo1.DisplayMember = "name";
combo1.ValueMember = "Index";


I'm not going to attempt to give you a complete solution here but I do hope ot send you in the right direction.

Basically you need to use a DataView (which is the "filtered" view of the original DataSet. So each time yo want to filter, you'll create a DataView assigning it the filter criteria.

http://msdn.microsoft.com/en-us/library/system.data.dataview.aspx

The link above should give you a working solution. Towards the bottom of the age they also have examples.

Once you have your DataView filtered the way you need to, you can iterate over it's rows to populate the drop downs in question.

Edited to provide simple steps for the OP.

Start simple. I'm assuming you know how to populate a ComboBox.

Step1: Get the Data in a DataSet Step2: Filter the DataSet using a DataView Step3: Populate the ComboBox using the DataView (instead of the DataSet)

pseudo code:

DataSet dt = GetInvDataTable();
DataView dv = new DataView(dt, "type = 15", null,
        DataViewRowState.CurrentRows);

Now you can use the DataView (the variable dv) to populate your CombobBox just like you were doing initially with the DataSet.

If you're using BindingSource then simply set the DataSource of the BindingSource to your DataView (dv in this case).

You don't mention the .NET version you're using but if you're using 3.5 or 4 you could also use linq to filter your DataSet. You'll need to add the DataSetExtensions assembly as a reference to you project.

DataTable invDataTable = GetInvDataTable();

EnumerableRowCollection<DataRow> query =
    from inv in invDataTable.AsEnumerable()
    where order.Field<int>("type") == 15
    select inv;

DataView dv = query.AsDataView();

bindingSource1.DataSource = dv;
0

精彩评论

暂无评论...
验证码 换一张
取 消