Reputation: 11
Here is my code should not accept duplicate rows in DataGridView but in my code, it's excepting:
should not accept duplicate rows THis is my datagridview it's not taking duplicate ID's but taking remaining fields to duplicate it should not duplicate filename, Lastname, and profession also
namespace Bind_DataGridView_Using_DataTable
{
public partial class Bind_DataGridView_Using_DataTable : Form
{
public Bind_DataGridView_Using_DataTable()
{
InitializeComponent();
}
DataTable table = new DataTable();
private void BtnAdd_Click(object sender, EventArgs e)
{
string idText = IDTxt.Text.Trim();
if (!string.IsNullOrEmpty(idText) && int.TryParse(idText, out int idValue))
{
if ((table.Select("Id = " + idValue)).Length == 0)
{
table.Rows.Add(idValue, fisrtTxt.Text.Trim(), SurNameTxt.Text.Trim(), ProfesTxt.Text.Trim());
//table.AcceptChanges();
dataGridView1.DataSource = table;
cleatTxts();
}
else
{
MessageBox.Show("Person Id already Exist");
}
}
else
{
label1.Text = "Person Id should not be empty && must be a valid int value";
}
}
}
}
Upvotes: 0
Views: 121
Reputation: 175
Distinct table by columns like this
table = table
.AsEnumerable()
.GroupBy(r => new
{
FirstName = r.Field<string>("FirstName"),
LastName = r.Field<string>("LastName"),
Profession = r.Field<string>("Profession")
})
.Select(group => group.First())
.CopyToDataTable();
Upvotes: 1
Reputation: 9479
I am not sure what is difficult about this. Use two if
statements, not one compound if
statement… If
ID is NOT duplicated then, if
first AND last names are not duplicated then add the row. You need to keep in mind, that if the ID IS a duplicate, then there is no need to check the names.
if ((table.Select("Id = " + idValue)).Length == 0) {
if ((table.Select("FirstName = '" + firstTxt.Text.Trim() +
"' AND LastName = '" + SurNameTxt.Text.Trim() + "'")).Length == 0) {
// add the row
}
}
Note the single quote " ' " before/after the text box values.
Upvotes: 0