我正在寫一個小ASP.net C#網頁,它不斷給我一個錯誤,指出: 沒有排在位置0拉SELECT查詢到一個DataTable和訪問它
我可能是做錯了,但這裏是我的一些代碼:
string SqlQuery = "SELECT * ";
SqlQuery += " FROM main_list";
SqlQuery += " WHERE ID = @FindID";
SqlConnection conn = new SqlConnection("server=???;database=contacts;User
ID=???;Password=???;");
conn.Open();
SqlCommand SqlCmd = new SqlCommand(SqlQuery, conn);
SqlCmd.Parameters.Add("@FindID",searchID);
SqlDataAdapter da = new SqlDataAdapter(SqlCmd);
try {
da.Fill(dt);
fillData(p);
}
catch {
txtId.Text = "ERROR";
}
而且FillData如下:
protected void fillData(int pos) {
txtId.Text = dt.Rows[pos]["ID"].ToString();
txtCompany.Text = dt.Rows[pos]["Company"].ToString();
txtFirstName.Text = dt.Rows[pos]["First_Name"].ToString();
txtLastName.Text = dt.Rows[pos]["Last_Name"].ToString();
txtAddress1.Text = dt.Rows[pos]["Address1"].ToString();
txtAddress2.Text = dt.Rows[pos]["Address2"].ToString();
txtCity.Text = dt.Rows[pos]["City"].ToString();
txtState.Text = dt.Rows[pos]["State"].ToString();
txtZipCode.Text = dt.Rows[pos]["ZipCode"].ToString();
txtPhoneNum1.Text = dt.Rows[pos]["Phone_Num"].ToString();
txtPhoneNum2.Text = dt.Rows[pos]["Phone_Num2"].ToString();
txtFax.Text = dt.Rows[pos]["Fax_Num"].ToString();
txtEmail.Text = dt.Rows[pos]["Email"].ToString();
txtNotes.Text = dt.Rows[pos]["Notes"].ToString();
txtCategory.Text = dt.Rows[pos]["Category"].ToString();
txtSubCategory.Text = dt.Rows[pos]["SubCategory"].ToString();
txtDateAdded.Text = dt.Rows[pos]["DateAdded"].ToString();
txtDateModified.Text = dt.Rows[0]["DateModified"].ToString();
}
這裏是調用的錯誤了:
protected void btnPrev_Click(object sender, EventArgs e) {
p--;
lblPage.Text = p.ToString();
fillData(p-1);
}
protected void btnNext_Click(object sender, EventArgs e) {
p++;
lblPage.Text = p.ToString();
fillData(p-1);
}
我想循環通過行[0]到行[1],但是有很多,但它給了我關於位置0或位置1沒有行的錯誤。它只填充一次,然後出錯。
編輯: 我試圖訪問已經訪問一行後數據庫返回的第二行。例如:行[0]可以很好地訪問,但是當我嘗試讀取行[1]時發現錯誤,並且說它在位置1沒有行。我可以修改代碼以返回行[1],它可以工作但是當我嘗試訪問行[0]時,它會中斷。這就是爲什麼我將變量(p)傳遞給fillData,所以它只能顯示行的值。謝謝!
編輯2:我相信這是因爲有一個回發,擦拭數據庫檢索到的值。有沒有辦法讓數據庫條目在回發後仍然保留?如果沒有,我猜我每次都必須查詢數據庫。
什麼意思「這僅填充一次,然後出現了錯誤」?爲什麼它應該多次填充? –
「但是很多有」 - 您是否嘗試迭代所有行? – emd
在調試模式下運行並查看當您嘗試從數據庫中提取數據並填充數據表時發生了什麼。也許你沒有從數據庫中獲取任何數據 – Pavenhimself