问题
I am trying to make it so that when you enter data into DataGridView
it first checks
if the ID textbox contains a string that exists in the DataGridView
ID column and throws an error if it finds a match.
If it does not match then the system can add the data.
I tried all kind of codes that people posted nothing worked. here is my latest.
private void btnadd_Click(object sender, EventArgs e)
{
Label label25 = new Label();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value.ToString() == IDtxtbox.Text)
{
label25.Text = "ID was already created,try some other number";
break;
}
else
{
dataGridView1.Rows.Add(IDtxtbox.Text, Nametxtbox.Text);
break;
}
}
}
回答1:
In the above code if the first row doesn't contain the value, you are adding the value.
You can check it this way:
var exists= dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.Select(row => row.Cells[0].Value.ToString())
.Any(x => this.IDtxtbox.Text == x);
if(!exists)
{
//Add rows here
}
Don't forget to add using System.Linq;
回答2:
Reza's answer is perfect if you were to use Linq, but if you are new to Linq and need a simpler solution here you go:
Idea is to check all the rows if that contains the ID. If any of the row has that ID, hasDuplicate
turns true. After checking all the rows (foreach
loop), then you should decide what to do (if-else
statements): like to display a message(label25.Text
) or add a new row(dataGridView1.Rows.Add
).
private void btnadd_Click(object sender, EventArgs e)
{
bool hasDuplicate=false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0] !=null && row.Cells[0].Value.ToString() == IDtxtbox.Text)
{
hasDuplicate = true;
break;
}
}
if(hasDuplicate)
label25.Text = "ID was already created,try some other number";
else
{
label25.Text.Clear();
dataGridView1.Rows.Add(IDtxtbox.Text, Nametxtbox.Text);
}
}
来源:https://stackoverflow.com/questions/34550214/c-sharp-visual-datagridview-search-if-textbox-cell-string