Remove duplicates from combobox which is bind to dataset - c#

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.

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

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.

Related

Single Datagridview Master-Details, no error but only shows "(Collection)"

I am using SQLite and I would like to use Master-Detail in a single DataGridView. No error return, I check the Master Table ("ASM") and the Details Table ("PART") their data are good. However, my gridAsmPart only shows one row with the word (Collection) on column PART. Any help will be appreciated.
public void LoadData()
{
var asm = new SQLiteDataAdapter("SELECT * FROM ASM", dB.connectionString);
var part = new SQLiteDataAdapter("SELECT * FROM PART", dB.connectionString);
var ds = new DataSet();
asm.Fill(ds, "ASM");
part.Fill(ds, "PART");
DataRelation data_relation = new DataRelation(
"ASM_PART",
ds.Tables["ASM"].Columns["PART"],
ds.Tables["PART"].Columns["PART"]);
ds.Relations.Add(data_relation);
gridAsmPart.DataSource = ds;
}
Edit 1: It seems that if I use the old DataGrid, it works.
Well… on the line of code… gridAsmPart.DataSource = ds; … ds is a DataSet and when you assign a DataSet to the grid as a DataSource, then you also need to specify “which” table in the DataSet the grid should display. That is what the grids DataMember is for.
Have you tried to set the grids DataMember property to something like…?
gridAsmPart.DataSource = ds;
gridAsmPart.DataMember = “ASM”;
Or if you want the “Part” table to display….
gridAsmPart.DataSource = ds;
gridAsmPart.DataMember = “PART”;

C#: Fill DataGridView with DataTable creates empty table

I searched the web and Stack Overflow and found lots of descriptions on how to fill a DataGridView with the content of a DataTable. But still it does not work for me. My DataGridView shows the correct number of columns and rows, but they appear empty.
I use following method:
public void ShowDataInGrid(ref DataTable table)
{
BindingSource sBind = new BindingSource();
dbView.Columns.Clear();
dbView.AutoGenerateColumns = false;
sBind.DataSource = table;
dbView.DataSource = sBind; //Add table to DataGridView
dbView.Columns.Add("Date", "Date");
}
Before this I created a DataGridView of name "dbView" via the designer. I am not even sure, whether I need sBind. Without it I can bind the table directly to dbView, with the same bad result.
I suspect my table is the problem. It origins from a database (SQLite) and has several columns and rows (one of the columns has the name "Date"). It is definately filled with readable data.
I mainly read the table in using following commands (after this I manipulate the data in several different steps, like changing strings and adding numbers...):
string sql = "select * from Bank";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
table.Load(reader);
reader.Close();
table.AcceptChanges();
I think the problem might be, that the table entries are stored as objects and not as string, and hence can't be shown. That's why I tried to force the content to be strings with the following change to my table:
DataTable dbTableClone = new DataTable();
dbTableClone.Load(reader);
SQLiteDataReader reader.Close();
dbTableClone.AcceptChanges();
string[] dBHeader = new string[dbTableClone.Columns.Count];
dBHeader = ReadHeaderFromDataTable(dbTableClone); //own funktion, which reads the header
DataTable table;
table.Clear();
//will first create dbTable as empty clone, so I can set DataTyp of each Column
table = dbTableClone.Clone();
for (int col = 0; col > dBHeader.Length; col++) //first set all columns as string
{
dbTable.Columns[col].DataType = typeof(string);
}
foreach (DataRow Row in dbTableClone.Rows)
{
dbTable.ImportRow(Row);
}
This did not help me neither.
Another idea: I found some comments on similar problems, where it got apparently solved with quote: "I designed columns in the VS datagridview designer. Not the column name, but the column DataPropertyName must match with fields in database." Unfortunately I don't seem to be able to do/understand this.
Following you see one row of my input table.
Try fetching and setting to GridView this way
SqlLiteConnection con = new SqlLiteConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=DB.mdf;Integrated Security=True");
con.Open();
SqlLiteDataAdapter adap = new SqlLiteDataAdapter("select * from Bank", con);
DataSet ds = new System.Data.DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
Comment everything you've done so far, try this and let me know if this works for you or not. Change connection according to your DB.
I solved the problem.
The DataTable was fine. The problem was the setup of my DataGridView dbView. I set up dbView in the designer and somehow gave it a datasource. Now I set the datasource to "none" (In "DataGridView Tasks") and my data appears as intended.
Thanks to M Adeel Khalid for looking at my stuff. Him assuring to me that my code for the link was right, made me find the solution eventually.
At the end I really only needed to use a single line:
dbView.DataSource = table;

How to add filtered row From Table inside Dataset that already get 3 other Tables?

I've problem in adding another Table and this is my Code
rptSalarList3_En SalaryListReport3 = new rptSalarList3_En();
ds = clsReports.ViewSalaryPaySlipListReport(parameters[0], PaySlip3.dtmFromDate, PaySlip3.dtmToDate);
dsReports.Tables.Clear();
dsReports.Tables.Add(ds.Tables[0].Copy());
dsReports.Tables.Add(ds.Tables[1].Copy());
dsReports.Tables.Add(ds.Tables[2].Copy());
DataTable dt1 = dsReports.Tables[0].Copy();
DataRow Dr = dt1.Rows[0];
DataRow[] result = dsReports.Tables[0].Select("SalaryItemName = 'Variable'");
dt1.Rows.Clear();
dt1.Rows.Add(result[0].ItemArray);
DataSet DsTaxable = new DataSet();
DsTaxable.Tables.Add(dt1);
dsReports.Tables.Add(DsTaxable.Tables[0]);
dsReports.Tables.Add(dsLogo.Tables[0].Copy());
dsReports.Tables[0].TableName = "SalaryListItems";
dsReports.Tables[1].TableName = "Preferences";
dsReports.Tables[2].TableName = "SalaryItemDetails";
dsReports.Tables[3].TableName = "SalaryItemTaxable";
The Problem is when having filter from first table it raise error message that said
(ex.Message = "DataTable already belongs to another DataSet.")
and I want to take the Filtered value from First Table and make it Table so I can add it To dsReports to Show in Crystal Report
Using .Copy() like other Tables helped me to get same data from first table which need to be filtered
and can added to current DataSet

Searching Access Database based on Textbox choice

private void btnSearchDB_Click(object sender, EventArgs e)
{
OleDbConnection accessConnect = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\ECM\ECM\ECM\ECM.mdb");
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM ECMeasurements WHERE [Job Number] LIKE " + txtJobNumber.Text, accessConnect);
da.Fill(dt);
dataGridView1.DataSource = dt;
}
There are also choices that can be searched by Date.....(txtDate.Text) and a comboBox (cbAlloyyTemper.Text). Do I write three different queries or can all the search criteria be together?
First: never use strings in the queries, but use Parameters.
Second: I would create 3 different queries, for easy debugging after. But all depends how much queries you can have, and your own comfort feeling.
This is not the way I would do this at all.
If you are looking at the same table each time you generate each query then you don't want to be querying the database each time. Instead you should load the data into a Data Table, and then query the Data Table in memory rather than the Database each time.
You need to create a Binding Source, and then set the data source for this object to your Data Table object.
For you gridView, you set the datasource for this object to your Binding Source.
Like so :-
OleDbConnection accessConnect = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\ECM\ECM\ECM\ECM.mdb");
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM ECMeasurements", accessConnect);
da.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
Now, any change in the state of the datatable reflects through to your gridview automatically.
To Query the DataTable you can use a DataView. DataView's allow you to search the Datatable with parameters like an SQL Statment. The syntax is off the top of my head, but its the method that you need to look at.
Look at Querying DataTables, using DataViews. There are many examples on the Internet.
In your scenario, its best suited.
Good Luck.

Get a part of an C# dataset and c opy it into another dataset

I have a dataset with one datatable. Now I want to set a filter on this table and copy the result to a dataset of the same type, so that I have a new dataset with only the result of the filtering. How can I do this?
Does the following code work?
ds.Tables[<table name>].DefaultView.RowFilter = "ProductId=5";
newDS = ds.copy();
You could do the following:
DataSet filterResult = new DataSet();
filterResult.Merge(inputDataset.Tables[0].AsEnumerable().Where(r => r["Property1"].ToString().Equals("SomeFilter") || r["Property2"].ToString().Equals("Some other filter")).ToArray());
Please note that DataTable offers Select method, but it throws some very weird exceptions from time to time, hence I prefer working with enumerable list of rows and lambdas instead.

Categories