Wednesday, September 10, 2008

Distinct records in datatable

Here is the easiest way to create a table with the distinct records. I have to add the currency symbols with the Currency name in the brackets. If these currency name was not the constraint then it was be really easy for me to add the items in the Combobox. I was able to add the items in the comboox and before adding just giving this condition 
if (ddlCurrencySymbol.Items.Contains("Textvalue")) continue;
Solve my purpose. But now the problem was i have to add the Currency name also in the list. So i can't just adding the name and use the above condition because it will create Euro for many countries. 

Now here what i have done to solve this issue.
I create two functions and use them to get rid of the Extra values.

public void SelectDistinctCurrency(string TableName, DataTable Table1, string CurrencyName)
        {
            DataTable dt = new DataTable(TableName);
            dt.Columns.Add(CurrencyName, SourceTable.Columns[CurrencyName].DataType);
            dt.Columns.Add("Text", SourceTable.Columns[CurrencyName].DataType);
            object FinalValue= null;
            foreach (DataRow dr in SourceTable.Select("", CurrencyName))
            {
                if (FinalValue == null || !(ColumnEqual(FinalValue, dr[FieldName])))
                {
                    FinalValue = dr[CurrencyName];
                    dt.Rows.Add(new object[] { FinalValue, dr["Text"] });
                }
            }
            ddlCurrencySymbol.DataSource = dt;
            ddlCurrencySymbol.DisplayMember = "Text";
            ddlCurrencySymbol.ValueMember = "Value";
        }
        private bool ColumnEqual(object A, object B)
        {

            if (A == DBNull.Value && B == DBNull.Value) 
                return true;
            if (A == DBNull.Value || B == DBNull.Value) 
                return false;
            return (A.Equals(B));  
        }

Hope this will hep you out.

No comments: