c# - 在 Sqlcommand 中使用 Remove 和 RemoveAt
问题描述
我想使用方法 Remove 和 RemoveAT 从数据库中删除组合框中的值我总是看到使用方法 add 但现在我想要 remove 和 RemoveAT
cmd.Parameters.RemoveAt(comboBox1.SelectedIndex);
我写了这段代码,但代码中有错误
private void Form1_Load(object sender, EventArgs e)
{
using(cnn = new SqlConnection(v))
{
using(cmd = new SqlCommand())
{
cmd.CommandText = "SELECT name_,age FROM Table_Group";
cmd.Connection = cnn;
cnn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr["age"]);
}
dr.Close();
cmd.Dispose();
cnn.Close();
}
}
}
删除例程
private void button5_Click(object sender, EventArgs e)
{
using (cnn = new SqlConnection(v))
{
using (cmd = new SqlCommand("DELETE FROM Table_Group WHERE age = @age", cnn))
{
cmd.Parameters.RemoveAt(comboBox1.SelectedIndex);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cnn.Close();
cmd.Dispose();
}
}
}
解决方案
既然你想要
从数据库中删除组合框中的值
您应该添加参数(要删除的内容)而不是删除它。像这样的东西
using (var cnn = new SqlConnection(v)) { //TODO: don't you forget "var"?
cnn.Open();
// let's have sql being readable
string sql =
@"DELETE
FROM Table_Group
WHERE age = @age";
// using will Dispose for you; there's no need in Close() and Dispose()
using (var cmd = new SqlCommand(sql, cnn)) {
//TODO: cmd.Parameters.Add is a better syntax
// I've put AddWithValue since I don't know corresponding RDBMS type
cmd.Parameters.AddWithValue("@age", comboBox3.SelectedValue);
cmd.ExecuteNonQuery();
}
}
RemoveAt
如果要从组合框而不是数据库中删除,则可以使用:
// Remove Selected Value
combobox3.RemoveAt(combobox3.SelectedIndex);
推荐阅读
- spring - 如何使用 JPQL 创建动态更新查询?
- android - ARCore 渲染一些自定义文本
- php - 如何在 Yii2 框架中设置邮件文件夹路径
- python - 使用 Python Turtle setworldcoordinates() 移动窗口
- html - 如何为 CLS 处理未知尺寸的图像
- excel - PowerQuery - 运行差异列 - 有点像运行总计
- raspberry-pi3 - agl-sota u-boot raspberrypi3 - 卡没有响应电压选择!设备 0:未知设备
- javascript - 是否可以在深度纹理上使用 texSubImage2D?
- visual-studio - 如何将 VisualStudio 2017 连接到特定的 AOS AX2012?
- angular - 取消订阅路由器事件