Reputation: 79
I have a datagridview, it has two columns and I get it's values from my SQL-Server table (3 columns). Can it possible to remove duplicate rows without using a new button?
It's my code:
foreach (DataRow r in d.Rows)
{
dgw.Rows.Add(r["c1"].ToString() + " " + r["c2"].ToString(), r["c3"]);
}
Thank you for your answers...
Edit: I need the answer with C# code, not sql.
Upvotes: 1
Views: 970
Reputation: 9771
You want to avoid duplicate records being displayed in data grid view so why not to select only those distinct records while querying your data.
string q = "SELECT DISTINCT c1, c2, c3 FROM mytable......";
And rather that iterating over each of row in datatable, you can simply use DataSource
property of DataTable
like,
SqlDataAdapter s = new SqlDataAdapter(q, c);
DataTable d = new DataTable();
s.Fill(d);
dgw.DataSource = dt;
Edit1:
You can check the row before adding it to data grid view like
foreach (DataRow r in d.Rows)
{
bool existingRow = dgw.Rows
.Cast<DataGridViewRow>().AsEnumerable()
.Any(x =>
Convert.ToString(x.Cells["Column1"].Value).Split(' ')[0] == r["c1"].ToString() &&
Convert.ToString(x.Cells["Column1"].Value).Split(' ')[1] == r["c2"].ToString() &&
Convert.ToInt32(x.Cells["Column2"].Value) == Convert.ToInt32(r["c3"])
);
if (!existingRow)
dgw.Rows.Add(r["c1"].ToString() + " " + r["c2"].ToString(), r["c3"]);
}
Where:
Column1
and Column2
are the columns in data grid view.c1
, c2
and c3
are the columns in data tableUpvotes: 1
Reputation: 706
Upvotes: 0