2012-01-16 51 views
0

我想使用.net读取数据库的所有记录,并且我在while循环中有一个逻辑错误,我无法理解问题是什么,如果有人可以看看,我将不胜感激。尝试保存数据库记录时在循环中出现逻辑错误

{ 
    System.Data.OleDb.OleDbConnection con; 
    DataSet dsl; 
    System.Data.OleDb.OleDbDataAdapter da; 
    public String accessDatabase() 
    { 
     initializecomponent(); 

     con = new System.Data.OleDb.OleDbConnection(); 
     con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Owner\\Documents\\CIS3052.mdb"; 
     dsl = new DataSet(); 
     String displayID = null; 
     String displayFname = null; 
     String displayLname = null; 
     String displayAge = null; 
     String displayJob = null; 
     String viewAll = null; 
     int inc = 0; 
     int MaxRows = 0; 


     string sql = "SELECT * FROM Employee"; 
     da = new System.Data.OleDb.OleDbDataAdapter(sql, con); 
     con.Open(); 
     da.Fill(dsl, "Employee"); 

     MaxRows = dsl.Tables["Employee"].Rows.Count; 
     while (inc != MaxRows -1) 
     { 

     DataRow dRow = dsl.Tables["Employee"].Rows[inc]; 
     displayID = dRow.ItemArray.GetValue(0).ToString(); 
     displayFname = dRow.ItemArray.GetValue(1).ToString(); 
     displayLname = dRow.ItemArray.GetValue(2).ToString(); 
     displayAge = dRow.ItemArray.GetValue(3).ToString(); 
     displayJob = dRow.ItemArray.GetValue(4).ToString(); 
     viewAll = viewAll + displayID + " " + displayFname + " " + displayLname + " " + displayAge + " " + displayJob + " "; 
     } 



     con.Close(); 
     con.Dispose(); 



     return viewAll; 
    } 


} 

}

+1

尽量多一点具体而言:你期望什么,你会得到什么? – DanTheMan 2012-01-16 22:40:17

+1

首先,你不会增加'inc',所以你只看第一行。 – 2012-01-16 22:44:01

回答

1

你为什么不尝试用一个for循环?

for(int i = 0; i < MaxRows; i++) 
{  
    DataRow dRow = dsl.Tables["Employee"].Rows[i]; 
    displayID = dRow.ItemArray.GetValue(0).ToString(); 
    displayFname = dRow.ItemArray.GetValue(1).ToString(); 
    displayLname = dRow.ItemArray.GetValue(2).ToString(); 
    displayAge = dRow.ItemArray.GetValue(3).ToString(); 
    displayJob = dRow.ItemArray.GetValue(4).ToString(); 
    viewAll = viewAll + displayID + " " + displayFname + " " + displayLname + " " + displayAge + " " + displayJob + " "; 
} 
+0

我试过这个,并取得了一些进展,但我只是得到显示的第一条记录的次数有记录 – Dumingu 2012-01-16 23:00:56

+0

它的工作原理只需要改变: DataRow dRow = dsl.Tables [“Employee”] .Rows [INC]; 至 DataRow dRow = dsl.Tables [“Employee”] .Rows [i]; 非常感谢=) – Dumingu 2012-01-16 23:02:42

0

替换 而 {

与 为(INC = MAXROWS -1!)(INT INC = 0; INC < MAXROWS; INC++) {

相关问题