删除列表框中的重复值

时间:2014-03-10 06:32:01

标签: c# listbox

我有一个列表框,我将它绑定到我的表位置并显示列位置。我在表格中插入了2个相同位置的值,我的列表框显示了我插入的2个相同值。那么,你能帮我在列表框中只显示一个相同的值吗? 到目前为止我只有这个代码:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string select;


            select = listBox1.SelectedValue.ToString();

            dataGridView1.DataSource = this.mAINDATABASEDataSet.tblPosition.Select("Position like '%" + select + "%'");




            int numRows = dataGridView1.Rows.Count;

            txtCount.Text = Convert.ToString(numRows);

            txtSearchCategory.Text = select.ToString();

            try
            {
                MAINDATABASEDataSet.tblCategorizationDataTable GetCategoryCommand1 = GetCategoryData(this.txtSearchCategory.Text.Trim());
                MAINDATABASEDataSet.tblCategorizationRow GetCategoryCommand2 = (MAINDATABASEDataSet.tblCategorizationRow)GetCategoryCommand1.Rows[0];

                this.txtSG.Text = GetCategoryCommand2.SalaryGrade.ToString();
                this.txtMales.Text = GetCategoryCommand2.Male.ToString();
                this.txtFemales.Text = GetCategoryCommand2.Female.ToString();

            }

            catch
            {
                MessageBox.Show("This Position is not saved yet!", "Information".ToUpper(), MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                txtSG.Text = "";
                txtMales.Text = "";
                txtFemales.Text = "";
            }
        }

        catch
        {
            return;
        }


    }

1 个答案:

答案 0 :(得分:0)

您可以通过在LINQ中选择distinct来完成此操作。请尝试使用此数据源:

 dataGridView1.DataSource = this.mAINDATABASEDataSet
.GroupBy(i => i.Position)
.Select(i => i.First())
.Where(i => i.Position.Contains(select));

在项目中包含using System.Linq;命名空间或引用它。如果这对您有用,请告诉我。