【问题标题】:ListView is displaying data which isn't stored in the databaseListView 正在显示未存储在数据库中的数据
【发布时间】:2016-06-05 00:27:34
【问题描述】:

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

任何帮助将不胜感激。

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 表中。

【问题讨论】:

    标签: c# database listview


    【解决方案1】:

    您应该在 SqlCommand 代码周围显式使用 SqlConnection(在 using 块中)。不确定您在执行查询时针对的是哪个连接。

    【讨论】:

    • 我以为我在做这个? SqlCommand cm = new SqlCommand("SELECT * FROM HighScore ORDER BY Score ASC", con);
    • 这是命令,但是它使用哪个连接来执行命令?您应该放置一个断点并检查以确定,但最好是用 using 包装您的 cammand 并明确设置连接。见:stackoverflow.com/questions/5460659/…
    • 所以你是说在类的顶部声明的 SqlConnection 是错误的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多