我在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);
}
}
答案 0 :(得分:1)
Repair方法不保证每个人都能完全恢复数据 数据库。某些形式的数据损坏无法修复 完全,无论选择的修复选项如何 应用
这可能是您的文件损坏的情况之一。
另请尝试在呼叫上方直接进行维修呼叫以填充列表中的数据。
这可能有所帮助。
答案 1 :(得分: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的不同方法
一个是Windows,另一个是如果您正在使用或计划使用ASP.NET
Populate a ListBox when using SQLDataReader
asp.net SqlDataReader example: how to use Read() method to populate ListBox