-1

我在 WinForms C# 中工作。

出于某种原因,当我想填充我的 listBox 时,它会停止并说我的数据库已损坏。我添加了一条维修线,然后代码运行,但没有任何反应。我的列表框未填充。

这是我使用的代码:

public void button1_Click(object sender, EventArgs e)
    {
        SqlCeConnection cn = new SqlCeConnection(@"Data Source = Database1.mdf");
        cn.Open();
        SqlCeCommand cm = new SqlCeCommand("SELECT * FROM tblprojects ORDER BY Projekt_liste ASC", cn);

        try
        {
            SqlCeDataReader dr = cm.ExecuteReader();

            while (dr.Read())
            {
                ListBox project_list = Application.OpenForms["Form1"].Controls["tabControl1"].Controls["tabPage1"].Controls["Project_list"] as ListBox;
                project_list.Items.Add(dr["Projekt_liste"].ToString());
            }
            cn.Close();
            cn.Dispose();
        }
        catch (Exception ex)
        {
        }
    }

    public void button2_Click(object sender, EventArgs e)
    {

        SqlCeConnection cn = new SqlCeConnection();

        SqlCeEngine engine = new SqlCeEngine("Data Source = Database1.mdf");

        if (false == engine.Verify())
        {
            MessageBox.Show("Database is corrupted.");
            engine.Repair(null, RepairOption.RecoverAllPossibleRows);
        }
    }
4

2 回答 2

1

来自微软网站

修复方法不保证对每个数据库都进行完整的数据恢复。无论应用程序选择了何种修复选项,某些形式的数据损坏都无法完全修复。

这可能是您的文件已损坏的情况之一。

也请尝试直接在呼叫上方进行维修呼叫以填充列表中的数据。

这可能会有所帮助。

于 2012-10-01T13:17:49.130 回答
1

例如,如果您想加载项目

1. make sure you have a ListBox on the winform
2. name the ListBox 
3. Create a ListItem 
4 Add the ListItem to the ListBox

while(dr.Read())
{
  ListViewItem obj=new ListViewItem(Convert.ToString(dr[0]),Convert.ToString(dr[1]);
  //in object of ListViewItem give display member at first and give value member at second position 
  listView1.Items.Add(obj); // add object to the listbox
}

这里有一些链接,您也可以使用它们来展示如何填充 ListBox 的不同方法

one is Windows and the other will be if you are using or plan to use ASP.NET

Populate a ListBox when using SQLDataReader

asp.net SqlDataReader example: how to use Read() method to populate ListBox

Populate ASP.NET ListBox using SqlDataReader

于 2012-10-01T13:38:39.187 回答