首页 > 解决方案 > 选择一个包含子类别的类别并将它们放入 DataGridView 中,没有类别重复

问题描述

我很抱歉标题不清楚,但我不知道如何准确地解释我想要什么,所以用图片会更容易。

编程语言:C#

我有三张桌子voltagecatenary_typetype_into_voltage

在表格中voltage,我们有电压等级catenary_type的名称,在接触网类型的名称中,type_into_voltage我们可以将电压等级与接触网类型相关联。

我想显示DataGridView与其电压电平相关的所有接触网类型,所以我实际上是使用返回 DataTable 的代码选择数据:

internal DataTable SelVoltType()
        {
            DataTable dt = new DataTable();

            using (SqlConnection connection = Program.GetOpenedSqlConnection())
            using (SqlCommand cmd = new SqlCommand("SELECT tiv.id_voltage, volt.name 'Tension', tiv.id_type, cattype.name as 'Types de caténaire' " +
                "FROM [allocation_schematic.types].type_into_voltage tiv " +
                "INNER JOIN [allocation_schematic.types].catenary_type cattype ON cattype.id = tiv.id_type " +
                "INNER JOIN [allocation_schematic.types].voltage volt ON volt.id = tiv.id_voltage; ", connection))
            using (SqlDataAdapter DataAdapter = new SqlDataAdapter(cmd))
                DataAdapter.Fill(dt);

            return dt;
        }

我把它直接放到DataGridView.DataSource.

它给了我这个

但我想要这样没有重复的电压电平

有人可以帮我吗?谢谢

标签: c#sqldatagridviewdatatableduplicates

解决方案


最简单的方法是在创建表格后移除电压。尝试以下:

           string oldVoltage = "";

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string tension = (string)dt.Rows[i]["Tension"];
                if (tension == oldVoltage)
                {
                    dt.Rows[i]["Tension"] = string.Empty;
                }
                else
                {
                    oldVoltage = tension;
                }
            }

推荐阅读