ListView正在显示未存储在数据库中的数据

时间:2016-06-04 15:50:39

标签: c# database listview

我的程序显示玩家得分与他们选择的别名,问题是我有大量的测试运行存储在数据库中所以我删除了表的所有条目,但它们仍然显示在列表视图中?

任何帮助都将不胜感激。

public partial class Leaderboard : Form
{

    public Leaderboard()
    {
        InitializeComponent();
    }

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=F:\Graded\WindowsFormsApplication2\WindowsFormsApplication2\bin\Debug\SusData.mdf;Integrated Security=True;Connect Timeout=30");

    private void Leaderboard_Shown(object sender, EventArgs e)
    {
        //try catch for opening the connection to the database
        try
        {
           con.Open();//Opening the connection to the database
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            Application.ExitThread();//if the database can't be opened the application will exit
        }
    }



    private void button1_Click(object sender, EventArgs e)
    {

        SqlCommand cm = new SqlCommand("SELECT Alias, Score FROM HighScore ORDER BY SCORE ASC");//SqlCommand allows for SQl commands to be used in the code of c#
        try//try catch for loading the users highScores
        {

            SqlDataReader DR = cm.ExecuteReader();
            while (DR.Read())
            {
                ListViewItem item = new ListViewItem(DR["Score"].ToString());//Filling the list view with users Scores
                item.SubItems.Add(DR["Alias"].ToString());//Filling the list view with users Alias
                listView1.Items.Add(item);//Adding everything

            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);//Messagebox in case theres an error loading the scores to the ListView

        }
    }

我在数据库中有两个表,玩家得分和别名'存储在HighScore表中。

1 个答案:

答案 0 :(得分:0)

您应该在SqlCommand代码周围明确使用SqlConnection(在using块中)。在您进行查询时,不确定您正在执行哪种连接。