2

I have a xml file in my project. I am reading the file through the below code in to combobox cbProduct. The problem is that the cbProduct is displaying duplicate text values. How to make them distinct?

I have gone through some links but there way of approach is not related to dataset.
I implemented the below code:

DataSet ds = new DataSet();
ds.ReadXml(@"..\..\stock.xml");
cbProduct.DataSource = ds.Tables[0];
cbProduct.DisplayMember = "productname";

optional: If you have time it will be appreciable if you explain the process because I am new to .net or provide a link atleast to refer (not msdn).

Please Help.
Thanks in advance.

Community
  • 1
  • 1
Mr_Green
  • 40,727
  • 45
  • 159
  • 271

2 Answers2

2

Do this

DataSet ds = new DataSet();
ds.ReadXml(@"..\..\stock.xml");
DataTable dt = ds.Tables[0].DefaultView.ToTable(true, "productname");
cbProduct.DataSource = dt;
cbProduct.DisplayMember = "productname";

Third code line creates a new table which will have distinct values based on productname column. For More read this

This code is here

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • thanks this working. but what if I have more columns. How to solve this problem. I tried this `DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);` but it is showing dll files from second column. (first column is good). – Mr_Green Oct 06 '12 at 06:21
  • I solved this by creating different datatable objects for different columns. I think this is not a correct way of approach. – Mr_Green Oct 06 '12 at 06:22
  • well I need some suggestion. I am using the [code something like this](http://ideone.com/oaN6e). without creating data tables. Is it a good approach? – Mr_Green Oct 06 '12 at 06:30
  • This is also good. if that datatable(having default values) is not used anywhere again then your code is fine. – Nikhil Agrawal Oct 06 '12 at 06:47
  • ok thanks...... please check my [new question](http://stackoverflow.com/q/12757461/1577396) if you are free – Mr_Green Oct 06 '12 at 06:48
1

You can bring distinct values from database or you can get distinct values from c# data table into new c# data table and bind it to dropdown. How to select distinct value.

Community
  • 1
  • 1
Adil
  • 146,340
  • 25
  • 209
  • 204
  • Thankyou for response. I tried this and i getting error. [Here is my code](http://ideone.com/FbFyC). The error is -- "Object reference not set to an instance of an object." – Mr_Green Oct 06 '12 at 06:07