0

我正在使用 Microsoft SQL Server 和 Visual Studio-C# 2010 Ultimate。我有一个 ListView 和其中的一些项目。当我选择一个项目并单击按钮时,我想删除它,但我无法编写 SqlCommandtext,也找不到 ListView 的选择事件。

4

5 回答 5

1

使用listview c#从数据库中删除选定的数据

private void btnlvdeleterow_Click(object sender, EventArgs e)
{
      foreach (int i in Listview2.SelectedIndices)
        {
            string test = Listview2.Items[i].Text;
            Listview2.Items.Remove(Listview2.Items[i]);
            SQLiteCommand conn = new SQLiteCommand();
            conn.Connection = DbClass1.GetConnection();
            string del = "delete from UserData where UserName='" + test + "'";
            int result=dbclass1.ExecuteAndReturn(del);
        }
}
于 2014-06-05T13:58:58.770 回答
0
 protected void listview1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
     //This retrieves the selected row 
     ListViewItem  item= listview1.Items [e.ItemIndex];

     //  Fetch the control for ProductId using findControl
      int productId=int.Parse((item.Findcontrol("ProductID") as TextBox).Text);

     //then use this column value in your sqlcommand

   using( SqlCommand cmd = new SqlCommand
        ("delete from Products where ProductID=@ProductId", connection  ))
    {
    command.Parameters.Add(new SqlParameter("ProductId", productId));
     //Then execute the query
    }
    }
于 2012-07-30T12:35:08.950 回答
0

ListView 有一个可用的 SelectedIndex 属性。当您单击按钮时,传递此索引,然后您的 Sql 查询将类似于 delete from Products where ProductID = 'obj.ID' 其中 obj 是从 listView.SelectedIndex 获得的

于 2012-07-30T12:31:03.170 回答
0
try
            {
                for (int j = 0; j <= listView2.Items.Count - 1; j++)
                {
                    string test = listView2.SelectedItems[j].SubItems[1].Text;
                    string MyConnection2 = "datasource=localhost;port=3306;username=root;password=root";
                    string Query = "delete from TABLE_NAME where COL_NAME='" + test + "'";
                    MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
                    MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
                    MySqlDataReader MyReader2;
                    MyConn2.Open();
                    MyReader2 = MyCommand2.ExecuteReader();

                    while (MyReader2.Read())
                    {
                    }
                    MyConn2.Close();
                    MessageBox.Show("Data Deleted");
                   // txtCustomerName.Text = test;
                    //listView2.Items.Remove(listView2.Items[i]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
于 2016-03-02T09:03:30.337 回答
-1

您正在寻找的事件应该是 ListView.ItemSelectionChanged 其中 eventArgs 包含选定的项目

于 2012-07-30T12:27:41.970 回答