【问题标题】:How to Compare Data gridview and Database field for Update Process如何比较更新过程的数据网格视图和数据库字段
【发布时间】:2017-04-28 22:31:57
【问题描述】:

我正在做 winforms.. 我正在比较 datagridview 列值和 db 值..

如果数据库中存在DataGridView列,如果不存在,我想做更新过程,我想做插入过程。

我试过这段代码

字符串结果JewelId = null;字符串 QueryJewelId = null;

private void AddStockTable()
{
    try
    {
        Sqlcon = objDB.DBConnection();


        QueryJewelId= "Select JewelId from tblStock";

        Sqlcmd = new SqlCommand(QueryJewelId, Sqlcon);


        dr = Sqlcmd.ExecuteReader();

        if (dr.HasRows)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                while (dr.Read())
                {
                    resultJewelId = dr.GetString(0);

                    if (resultJewelId == dataGridView1[0, i].Value.ToString())
                    {
                        MessageBox.Show("Update process");

                    }
                    else
                    {
                        MessageBox.Show("Insert Process");
                    }
                }
            } 

        }
    }
    catch (Exception ex)
    { MessageBox.Show(ex.ToString()); }
}

虽然条件工作正常..但我不知道如何在 for 循环中移动下一行值..

请支持我。

【问题讨论】:

  • SQL 有一个 WHERE 语句,可让您在不循环代码的情况下找到值。

标签: c# winforms datagridview


【解决方案1】:

最好的办法是编写一个存储过程来检查数据是否存在并相应地更新数据库

Create procedure AddorUpdateStock
@JewelId it,
--remaining columns
if not exists(select JewelId from tblstock  where JewelId = @JewelId)
begin
--insert
end
else
begin
--update
end

您遍历 datagridview 中的所有行并调用此过程

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多