c# - 在datagridview循环内重复记录搜索
问题描述
我用一个按钮将datagridview中的记录记录到数据库中,然后进行删除。我写了一个重复记录的方法,该方法有效,但有时循环出现问题。方法如下;
void mukerrer()
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
baglanti.Open();
SqlCommand komut = new SqlCommand("Select * from STOKLAR WHERE barkod_no='" + Int64.Parse(dataGridView1.Rows[i].Cells["barkod_no"].Value.ToString()) + "'", baglanti);
//komut.Parameters.AddWithValue("@p1", barkod.Substring(3, 13));
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
durum = false; // Kayıt varsa false
}
else
{
durum = true;
};
baglanti.Close();
}
}
在注册过程中,我调用方法如下,但我认为计数操作给我一个错误。(dataGridView1.Rows.Count-1) 但是当它发出一次警告时,即使我从 datagridview 中删除该记录,它也会再次发出警告。
private void simpleButton1_Click(object sender, EventArgs e)
{
mukerrer();
if (durum == true)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
baglanti.Open();
SqlCommand komut = new SqlCommand("insert into STOKLAR(barkod_no,toplam_paket_no,paket_no,raf_id,create_date) values (@barkod_no,@toplam_paket_no,@paket_no,@raf_id,@create_date)", baglanti);
komut.Parameters.AddWithValue("@barkod_no", Int64.Parse(dataGridView1.Rows[i].Cells["barkod_no"].Value.ToString()));
komut.Parameters.AddWithValue("@toplam_paket_no", int.Parse(dataGridView1.Rows[i].Cells["toplam_paket_no"].Value.ToString()));
komut.Parameters.AddWithValue("@paket_no", int.Parse(dataGridView1.Rows[i].Cells["paket_no"].Value.ToString()));
komut.Parameters.AddWithValue("@raf_id", dataGridView1.Rows[i].Cells["raf_id"].Value.ToString());
komut.Parameters.AddWithValue("@create_date", dataGridView1.Rows[i].Cells["create_date"].Value);
komut.ExecuteNonQuery();
baglanti.Close();
}
textRaf.Text = "";
MessageBox.Show("Kayıtlar Eklenmiştir.");
this.ActiveControl = textRaf;
}
else
{
MessageBox.Show("Sistemde kayıtlı olan barkod var!", "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
解决方案
你应该在 durum == false 之后打破 for 循环。
像这样的东西:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
baglanti.Open();
SqlCommand komut = new SqlCommand("Select * from STOKLAR WHERE barkod_no='" + Int64.Parse(dataGridView1.Rows[i].Cells["barkod_no"].Value.ToString()) + "'", baglanti);
//komut.Parameters.AddWithValue("@p1", barkod.Substring(3, 13));
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
durum = false; // Kayıt varsa false
baglanti.Close();
break;
}
else
{
durum = true;
};
baglanti.Close();
}
推荐阅读
- python - 仅编码无符号整数时的base64字符串长度计算
- php - datalist country 选择要显示的州
- html - 使用table-bordered类时如何让一些表格单元格边框消失?
- python - 为什么 torch.lstsq 的输出与 np.linalg.lstsq 有很大不同?
- python - 替换值但不显示python数组中的完整数据
- python-3.x - Nonetype 和 datetime.datetime 之间的 Django Polling App TypeError
- c# - 如何配置 Autofac,以便每次新建时都会创建我的 DbContext?
- python - “未找到 Windows 控制台。您正在运行 cmd.exe 吗?”
- python - 如何在 discord.py 中创建 NSFW 命令?
- c - 结构和指针如何作用