【问题标题】:Transferring from listview to listbox and updating SQL Server database从列表视图转移到列表框并更新 SQL Server 数据库
【发布时间】:2018-02-11 17:03:26
【问题描述】:

我有一个表单,它使用 SQL 查询将数据从 listview 传输到 listbox。我没有错误,SQL 代码正在读取查询并将数据从listview 传输到listbox 正在工作,但似乎我的SqlCommand 没有运行/更新我的datagridview。我不知道这是否适合放置SqlCommand - 请帮我解决这个问题。

for (int intCount = 0; intCount < listViewOrders.Items.Count; intCount++)
{
    listBoxInvoice.Items.Add(listViewOrders.Items[intCount].Text);
    listBoxInvoice.Items.Add("                              x" + listViewOrders.Items[intCount].SubItems[2].Text +
                             "                  @                " + listViewOrders.Items[intCount].SubItems[1].Text);

    connect.Open();

    SqlCommand cmd = new SqlCommand("UPDATE tblProducts SET productQuantity = productQuantity - " +
                            listViewOrders.Items[intCount].SubItems[2].Text + "WHERE productName = '" + listViewOrders.Items[intCount].Text + "'", connect);

    connect.Close();
}

dataGridProd.Update();
dataGridProd.Refresh();

提前谢谢你。欢迎任何类型的回复。

【问题讨论】:

  • 你在运行时有什么错误吗?
  • @JericCruz 到目前为止没有错误,但它没有更新 productQuantity
  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入 - 查看Little Bobby Tables
  • 你只是定义 cmd - 但你永远不会执行(运行)它.....你需要使用cmd.ExecuteNonQuery()(在connect.Close() 调用之前)实际运行该代码 .....

标签: c# sql-server winforms listview listbox


【解决方案1】:

我认为这是您查询中的一个空格,特别是在WHERE 子句中。

所以这样做:

SqlCommand cmd = new SqlCommand("UPDATE tblProducts SET productQuantity = productQuantity - " + listViewOrders.Items[intCount].SubItems[2].Text + " WHERE productName = '" + listViewOrders.Items[intCount].Text + "'", connect);
cmd.ExecuteNonQuery();

或者如果您使用的是 C#6+,则使用字符串插值。

var cmd = new SqlCommand($@"UPDATE tblProducts SET productQuantity = productQuantity - {listViewOrders.Items[intCount].SubItems[2].Text} WHERE productName = '{listViewOrders.Items[intCount].Text}'", connect);
cmd.ExecuteNonQuery();

不要忘记使用ExecuteNonQuery 执行它,因为你是 更新数据。

并确保listViewOrders.Items[intCount].Text 具有值。你可以添加一个断点来检查它。

===============更新=================

如果你使用 SQL 参数来避免 SQL 注入会更好。

SqlCommand cmd = new SqlCommand("UPDATE tblProducts SET productQuantity = productQuantity - @quantity WHERE productName = @productName", connect);
cmd.Parameters.AddWithValue("@quantity", listViewOrders.Items[intCount].SubItems[2].Text);
cmd.Parameters.AddWithValue("@productName", listViewOrders.Items[intCount].Text);
cmd.ExecuteNonQuery();

【讨论】:

  • 非常感谢。我只是忘记了 cmd.ExecuteNonQuery();
  • 还有一件事先生。如何更新按钮上的 datagridview?我正在使用 dataGridView.Refresh();和更新();但没有任何效果。萨乌利廷爵士。马拉曼萨拉马特?
  • 您可以先更新绑定到数据网格的数据源,然后执行dataGridProd.Refresh()
猜你喜欢
  • 2018-04-22
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 2014-09-25
  • 2014-12-06
  • 2010-09-13
  • 1970-01-01
相关资源
最近更新 更多