Nida Nida - 2 months ago 6
ASP.NET (C#) Question

How to avoid duplicate values from dataset in texbox

I have written a function like below

private void PrepUpdate()
{
LicenceBL lbl = new LicenceBL(0);
DataSet lds = new DataSet();
lbl.FetchForEdit(lds, AgentId,BrokerId);
string output ="";
for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
{
output = output + lds.Tables[0].Rows[i]["LicenceTypesNames"].ToString();
output += (i < lds.Tables[0].Rows.Count) ? "," : string.Empty;
}
txtLicenseType.Text = output;
}


It fetch all the LicenceTypesNames from dataset and split them with ',' and then places them in textbox. If dataset contains duplicate entries for licencetypesnames column, they are also inserted in the textbox... Please help me!!!

Answer

Use HashSet<string>, which takes only unique values in the Add method

private void PrepUpdate()
{
    LicenceBL lbl = new LicenceBL(0);
    DataSet lds = new DataSet();
    lbl.FetchForEdit(lds, AgentId,BrokerId);

    HashSet<string> values = new HashSet<string>();

    for (int i = 0; i < lds.Tables[0].Rows.Count; i++)
    {
        values.Add(lds.Tables[0].Rows[i]["LicenceTypesNames"].ToString());
    }

    txtLicenseType.Text = string.Join(", ", values.ToList());
}