从列表框和数据库中删除

时间:2017-01-08 14:47:50

标签: c# database visual-studio listbox

这是我的Form1.cs代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VoetbalApp
{
    public partial class VoetbalApp : Form
{
    Administration admin = new Administration();

    public VoetbalApp()
    {
        InitializeComponent();

        LoadSpelers();
    }


    public void LoadSpelers()
    {


        string filter = tbNaam.Text;
        lbSpelers.Items.Clear();

        List<Speler> spelers = admin.GetAllSpelers(filter);

        foreach (Speler s in spelers.Where(s => s.Name.Contains(filter)))
        {
            lbSpelers.Items.Add(s);
        }

    }

    public bool ClubCorrect(string club)
    {

        if (club != "Unitas 59")
        { 
            return false;
        }

        else
        {
            return true;
        }
    }

    private void btAdd_Click(object sender, EventArgs e)
    {
        string spelerNaam = tbAddNaam.Text;
        string spelerClub = tbAddClub.Text;

        if (ClubCorrect(spelerClub))
        {
           admin.AddSpeler(spelerNaam, spelerClub);

            LoadSpelers();
        }

        else
        {
            MessageBox.Show("De door u ingevoerde club is niet juist."
                );
        }
    }

    private void btDelete_Click(object sender, EventArgs e)
    {
        int id;
        Int32.TryParse(tbId.Text, out id);

        bool verwijderenIsGelukt = admin.RemoveSpeler(id);

        if (verwijderenIsGelukt)
        {
            LoadSpelers();
            MessageBox.Show("Speler met ID" + id + " is succesvol verwijderd.");
            tbId.Text = "";
        }

        else
        {
            MessageBox.Show("Er is iets mis gegaan bij het verwijderen van student met ID" + id + ".", "Verwijderen is mislukt.", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void tbNaam_TextChanged(object sender , EventArgs e)
    {
        LoadSpelers();
    }

    private void tbNaam_TextChanged_1(object sender, EventArgs e)
    {
        LoadSpelers();
    }


}
}

我的第二个代码是Administration.cs

 using System.Collections.Generic;
 using System.Data;

 // For SQL server operations
 using System.Data.SqlClient;
 using System.Windows.Forms;

 namespace VoetbalApp
 {

class Administration
{


    public static string connectionString = @"Initial Catalog=Speler.mdf;Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + Application.StartupPath + @"\Speler.mdf;Integrated Security=True";
    public SqlConnection conn = new SqlConnection(connectionString);






    List<Speler> spelers = new List<Speler>();


    /// <param name="name">De naam van de nieuwe speler.</param>
    /// <param name="club">De club van de nieuwe speler.</param>
    /// 


    public void AddSpeler(string name, string club)
    {

            conn.Open();
            Speler speler = new Speler();
            speler.Name = name;
            speler.Club = club;
            string query = @"INSERT INTO Speler (Name, Club) OUTPUT Inserted.ID 
                 VALUES (@name, @club)";
            SqlCommand cmd = new SqlCommand(query, conn);
            cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = speler.Name;
            cmd.Parameters.Add("@club", SqlDbType.NVarChar).Value = speler.Club;
            speler.ID = (int)cmd.ExecuteScalar();
            conn.Close();


    }





    /// <param name="ID">Het ID van de speler die verwijderd moet worden.</param>
    /// <returns>Geeft true terug bij succes, en anders false.</returns>
    public bool RemoveSpeler(int ID)
    {
        int nrOfRowsAffected = 0;


        conn.Open();
            foreach (Speler s in spelers)
            {

                if (s.ID == ID)
                {

                    string query = "DELETE FROM Speler WHERE ID = " + ID;
                    SqlCommand cmd = new SqlCommand(query, conn);


                    nrOfRowsAffected = cmd.ExecuteNonQuery();
                    spelers.Remove(s);


                    break;
                }
            }


        conn.Close();
        return nrOfRowsAffected > 0;
    }


    /// <param name="filter">De filter is om spelers te zoeken van de database.</param>
    /// <returns>Een lijst van spelers waarvoor de filter is toegepast.</returns>
    public List<Speler> GetAllSpelers(string filter)
    {



        spelers = new List<Speler>();


        string query = "SELECT S.* FROM Speler S";



        if (filter != "")
        {
            query += " WHERE Name LIKE '%" + filter + "%' OR Club LIKE '%" + filter + "%'";
        }



        conn.Open();
        SqlCommand cmd = new SqlCommand(query, conn);


        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {

                Speler speler = new Speler();


                speler.ID = reader.GetInt32(0);
                speler.Name = reader.GetString(1);
                speler.Club = reader.GetString(2);


                spelers.Add(speler);
            }
        }


        conn.Close();
        return spelers;

    }
}
}

所以问题出现在administration.cs的 RemoveSpeler 和form1.cs中的 btDelete 。谢谢您抽出宝贵时间 我的帖子大部分是代码,所以我需要添加更多细节或者我不能发布它... 所以我想要做的是我有一个文本框(tbID),我需要输入Speler的ID号,然后按一个按钮(btDelete)从列表框中删除带有我输入的ID的Speler /数据库。但由于某种原因,它只是没有做任何事情,没有错误或任何事情。 而这仍然不够详细,所以我仍然无法发布它所以我只需要在这里输入更多东西,我不知道还有什么可以在这里输入。

1 个答案:

答案 0 :(得分:1)

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public static class admin
    {
        public static bool RemoveSpeller(int id, ListBox listbox)
        {

            if (listbox.Items.Contains(id.ToString()))
            {
                MessageBox.Show("Exists");
                listbox.Items.Remove(id.ToString());
                try
                {

                    SqlConnection con = new SqlConnection(/*Connection string goes here*/);

                    con.Open();
                    SqlCommand com = new SqlCommand("DELETE FROM Speler WHERE id = '" + id + "'", con);

                    com.ExecuteNonQuery();

                    con.Close();
                    return true;

                }
                catch (SqlException)
                {
                    MessageBox.Show("Something went wrong while removing the item");
                    return false;

                }
            }
            else
            {
                MessageBox.Show("Wasn't found!");
                return false;
            }


        }
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {

           admin.RemoveSpeller(Convert.ToInt16(tbId.Text), yourlistboxname);

        }
    }
}