我想從accessDatabase中寫入特定的單元格數據到數據表中。我使用SELECT查詢來獲取這些數據,但是當將數據寫入數據表中的特定單元格時,循環在迭代之前會中斷一次,即使它應該迭代兩次。爲什麼我的代碼在數據表中填充單元時停止?
下面是我使用的代碼:
DataTable dt = new DataTable(); // Creates Table
dt.Clear();
dt.Columns.Add("Hol/Abs", typeof(string)); // Column 0
dt.Columns.Add("FirstDay", typeof(DateTime)); // Column 1
dt.Columns.Add("LastDay", typeof(DateTime)); // Column 2
dt.Columns.Add("TotalDays", typeof(int)); // Column 3
dt.Columns.Add("Reason", typeof(string)); // Column 4
LblName.Text = PassName; //Loads Name
string ConnString = @"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
string Query = "SELECT PayrollNo FROM [Employee] WHERE (FirstName + ' ' + LastName) = @Name";
string CountQuery = "SELECT COUNT(*) FROM [Holiday]";
string GetStartQuery = "SELECT StartDate FROM [Holiday] WHERE PayrollNo = @PayrollNo";
string GetEndQuery = "SELECT EndDate FROM [Holiday] WHERE PayrollNo = @PayrollNo";
string GetReasonQuery = "SELECT Reason FROM [Holiday] WHERE PayrollNo = @PayrollNo";
using (OleDbConnection conn = new OleDbConnection(ConnString))
using (OleDbCommand GetPayroll = new OleDbCommand(Query, conn))
{
conn.Open();
GetPayroll.Parameters.Add("@Name", OleDbType.VarChar).Value = LblName.Text;
int GotPayroll = Convert.ToInt32(GetPayroll.ExecuteScalar()); //Uses Query to Get PayrollNo
OleDbCommand CountRowsInHol = new OleDbCommand(CountQuery, conn);
CountRowsInHol.Parameters.AddWithValue("@PayrollNo", OleDbType.Integer).Value = GotPayroll;
int HolidayCount = (int) (CountRowsInHol.ExecuteScalar()); //Uses CountQuery to Get HowMany lines are in [Holiday]
int LoopCount = 0;
while (LoopCount <= HolidayCount) //Will go though all Lines in [Holiday]
{
OleDbCommand GetStart = new OleDbCommand(GetStartQuery, conn);
OleDbCommand GetEnd = new OleDbCommand(GetEndQuery, conn);
OleDbCommand GetReason = new OleDbCommand(GetReasonQuery, conn);
GetStart.Parameters.Add("@PayrollNo", OleDbType.Integer).Value = GotPayroll;
GetEnd.Parameters.Add("@PayrollNo", OleDbType.Integer).Value = GotPayroll;
GetReason.Parameters.Add("@PayrollNo", OleDbType.Integer).Value = GotPayroll;
DateTime StartHold = Convert.ToDateTime(GetStart.ExecuteScalar());
DateTime EndHold = Convert.ToDateTime(GetEnd.ExecuteScalar());
string ReasonHold = (GetReason.ExecuteScalar()).ToString();
dt.Rows[LoopCount]["FirstDay"] = StartHold;
dt.Rows[LoopCount]["LastDay"] = EndHold;
dt.Rows[LoopCount]["Reason"] = ReasonHold;
LoopCount = LoopCount + 1;
}
}
我知道它的長,但它是非常基本的。代碼中斷..
dt.Rows [LoopCount] [「FirstDay」] = StartHold;
..不寫入數據表。 任何幫助或建議將不勝感激,也很開放,以更好地更好地格式化我的代碼的建議,所以它更容易閱讀和更普遍的標準。
我沒有看到你曾經填充數據錶行。一個好的做法是將代碼封裝在Try/Catch中,並閱讀異常消息。 – Crowcoder