简体   繁体   中英

How To Remove Duplication Of Data In DataGridView

I am developing a VB.NET application that uses a DataGridView control to display data from a database. Currently, it is displaying as follows:

54     john         NJ        HRA           1000   
54     john         NJ        DA            2500   
54     john         NJ        BP            12500

But I need to display it as follows:

54      john  NJ
                     HRA           1000   
                     DA            2500
                     BP            12500

Since ID, name and city are repeated, I do not need to display these again. How can I do this?

I think this can help you

DataTable dtDataSource = new DataTable();

dtDataSource.Columns.Add("A");
dtDataSource.Columns.Add("B");
dtDataSource.Columns.Add("C");

dtDataSource.Rows.Add(new object[] { "1", "1", "1" });
dtDataSource.Rows.Add(new object[] { "1", "1", "2" });
dtDataSource.Rows.Add(new object[] { "1", "1", "3" });
dtDataSource.Rows.Add(new object[] { "2", "1", "1" });
dtDataSource.Rows.Add(new object[] { "2", "1", "2" });
dtDataSource.Rows.Add(new object[] { "2", "1", "3" });

DataTable dtNew = dtDataSource.Clone();

for (int i = 0; i < dtDataSource.Rows.Count; i++)
{
    if (i > 0)
    {
        if (dtDataSource.Rows[i][0].Equals(dtDataSource.Rows[i - 1][0]))
        {
            dtNew.Rows.Add(new object[] { "", dtDataSource.Rows[i][1], dtDataSource.Rows[i][2] });
        }
        else
        {
            dtNew.Rows.Add(new object[] { dtDataSource.Rows[i][0], "", "" });
            dtNew.Rows.Add(new object[] { "", dtDataSource.Rows[i][1], dtDataSource.Rows[i][2] });
        }
    }
    else
    {
        dtNew.Rows.Add(new object[] { dtDataSource.Rows[i][0], "", "" });
        dtNew.Rows.Add(new object[] { "", dtDataSource.Rows[i][1], dtDataSource.Rows[i][2] });
    }
}

dataGridView1.DataSource = dtNew;

Your data should be ordered initially.

I tried to convert VB.Net here

If all you are doing is displaying data you could use a UNION of two SQL statements.

The first would retrieve the first three columns plus two columns with empty strings UNION SQL three columns with empty strings and the two columns of data. The field names of the first SQL statement will name the columns.

The data would be read only.

    SELECT F1, F2, F3, '' as F4, '' as F5 WHERE ...
    UNION
    SELECT '', '', '', F4, F5 WHERE ...

If you are retrieving data for more than one target the SQL will get a bit more complex.

your problem is occurring because of how your database is made.

are you using primary keys and foreign keys?

so that you can easily identify which records only to display

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM