如何从C#中的ListView中删除数据库所选项

时间:2012-07-30 11:46:04

标签: c# sql-server listview select

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

5 个答案:

答案 0 :(得分: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);
        }
}

答案 1 :(得分:0)

ListView有一个SelectedIndex属性。当您单击该按钮时,传递此索引,然后您的Sql查询将是这样的 从ProductID ='obj.ID'的产品中删除,其中obj是从listView.SelectedIndex

获得的

答案 2 :(得分: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
    }
    }

答案 3 :(得分: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);
            }

答案 4 :(得分:-1)

您要查找的事件应该是ListView.ItemSelectionChanged eventArgs包含所选项目的位置