C# Display DataGridView Rows Based on Similar ID from sql server

Sojib Hossen 0 Reputation points
2023-08-21T18:50:44.6966667+00:00

Display DataGridView Rows Based on Similar ID. My seem problem

Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other
A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,591 Reputation points Volunteer Moderator
    2023-08-21T23:13:20.3133333+00:00

    Simple group-by to see if there are duplicates. And rather than me write an elaborate code sample

    dups

    using System.Data;
    
    namespace WinFormsApp1;
    
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            dataGridView1.DataSource = MockedDataTable();
        }
    
        private void GroupByIdButton_Click(object sender, EventArgs e)
        {
            dataGridView2.DataSource = GroupData((DataTable)(dataGridView1.DataSource));
        }
    
        public static DataTable GroupData(DataTable dt) =>
            dt.AsEnumerable()
                .GroupBy(row => row.Field<int>("id"))
                .Select(g => 
                    g.OrderBy(r => r.Field<int>("id")).First())
                .CopyToDataTable();
    
        public static DataTable MockedDataTable()
        {
            var table = new DataTable();
    
            table.Columns.Add(new DataColumn("Id", typeof(int)));
            table.Columns.Add(new DataColumn("TaxRate", typeof(decimal)));
            table.Columns.Add(new DataColumn("Value", typeof(decimal)));
            table.Columns.Add(new DataColumn("TaxAmount", typeof(decimal)));
            table.Columns.Add(new DataColumn("FinalValue", typeof(decimal), "Value + TaxAmount"));
    
            table.Rows.Add(1, 5, 1000, 50);
            table.Rows.Add(1, 5, 2000, 100);
            table.Rows.Add(1, 10, 1000, 100);
            table.Rows.Add(2, 10, 2000, 200);
            table.Rows.Add(1, 15, 1000, 150);
            table.Rows.Add(2, 15, 2000, 300);
    
            return table;
    
        }
    }
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.