【发布时间】:2017-03-14 09:34:30
【问题描述】:
这其实是我第一次问。我试图搜索所有内容,但找不到答案。
我想从一开始就扫描我在 DataGridView 中的所有值以防止重复。我使用 Access 作为我的数据库。到目前为止,我只能检查选定的行,然后将其与文本框进行比较。 My current form.如果文本框值在所有数据中具有相似的项目名称,我需要禁用“添加”
这是我的代码。它只影响选定的行。不是所有的行。
string item = dgvInventory.Rows[dgvInventory.CurrentRow.Index].Cells[0].Value.ToString();
if (tbItem.Text == item)
{
btnAdd.Enabled = false;
lblAdd.Text = "Item name cannot be the same";
}
else
{
btnAdd.Enabled = true;
lblAdd.Text = "Accepted";
}
请帮忙?
我试图插入一个for 循环所以这是我现在的代码,但它只发生在最后一行。我在这里想念什么?或者我犯了什么错误
for (int x = 0; x < dgvInventory.Rows.Count; x++)
{
string item = dgvInventory.Rows[x].Cells[0].Value.ToString();
if (tbItem.Text == item)
{
btnAdd.Enabled = false;
lblAdd.Text = "Item name cannot be the same";
}
else
{
btnAdd.Enabled = true;
lblAdd.Text = "Accepted";
}
}
【问题讨论】:
-
你可以做一个
for循环然后在那里添加条件。像这样for (int i = 0; i < dataGridView1.Rows.Count; i++) -
有很多方法可以做到这一点:
for循环,foreach循环,Linq... -
@P.Pat 谢谢你的建议。我试过
for (int x = 0; x < dgvInventory.Rows.Count; x++)然后string item = dgvInventory.Rows[x].Cells[0].Value.ToString();不知何故它只适用于最后一行 -
调试代码,你会发现它只在最后一行不起作用。问题是你在每一行上设置
item,所以最后你得到了最后一行的值。您需要检查值是否与您在 for 循环中查找的值相同
标签: c# database ms-access datagridview