你好夥伴開發人員, 我想從函數返回一個Datatable用於我的代碼。 其登錄表,我有我的工作人員,並基於employeerole我做我的進一步導航。 但問題是每當我嘗試啓動查詢,查詢觸發並返回dataTable中的某些值,但是當我嘗試訪問它時,錯誤:「位置0沒有行」彈出。位置0沒有行,C#
我檢查DataTable是否爲null。
的DatabaseConnection類的初始化和對象的創建可以在這裏找到和我的功能(類聲明,構造函數和函數)
public class DatabaseConnection
{
const string strConnectionString = "DATA SOURCE =dilbert.humber.ca:1521/grok; USER ID =n00993435; PASSWORD= oracle;";
OracleConnection oracleConnection;
OracleCommand oracleCommand;
string query;
OracleDataReader oracleReader;
OracleDataAdapter oracleDataAdapter;
OracleCommandBuilder oracleCommandBuilder;
DataTable dataTable;
public DatabaseConnection()
{
try
{
oracleConnection = new OracleConnection(strConnectionString);
oracleCommand = new OracleCommand();
oracleCommand.Connection = oracleConnection;
oracleCommand.Connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
public DataTable Login(string u, string p)
{
try
{
string query = "select employeeid, username, password, firstname, lastname, employeerole from login where username='" + u + "' and password='" + p + "'";
oracleCommand.CommandText = query;
oracleDataAdapter = new OracleDataAdapter(oracleCommand);
dataTable = new DataTable();
oracleDataAdapter.Fill(dataTable);
return dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
finally
{
oracleConnection.Close();
}
}
}
我的實現:
private void pictureBox1_Click(object sender, EventArgs e)
{
if (txtUName.Text == null || txtUName.Text == "")
{
MessageBox.Show("Please Enter UserName");
}
else if (txtPassword.Text == null || txtPassword.Text == "")
{
MessageBox.Show("Please Enter Password");
}
else
{
string username = txtUName.Text;
string password = txtPassword.Text;
DatabaseConnection obj = new DatabaseConnection();
DataTable dt = new DataTable();
dt = obj.Login(username, password);
if (dt == null)
{
MessageBox.Show("User with these credentials not found in our Database. Please contact the Admin");
}
else
{
DataRow row = dt.Rows[0];
string role = row[5].ToString();
if (role == "ADMIN")
{
Admin madmin = new Admin();
this.Hide();
madmin.Show();
}
else if (role == "MANAGER")
{
BranchManager badmin = new BranchManager();
this.Hide();
badmin.Show();
}
else if (role == "EMPLOYEE")
{
MainBank obj2 = new MainBank();
obj2.Show();
this.Hide();
}
else
{
lblWarning.Visible = true;
lblWarning.Text = "Invalid Login Credentials.";
txtUName.BackColor = Color.Red;
txtPassword.BackColor = Color.Red;
txtUName.Focus();
}
}
}
}
的數據是正確的在Oracle中檢索:
我很無語,爲什麼這個錯誤是 彈出。
這是所創建的查詢:"select employeeid, username, password, firstname, lastname, employeerole from login where username='ADMIN' and password='ADMIN'"
這對我來說似乎很好,因爲我試圖在編輯器上運行相同的程序,它的工作原理!有什麼我失蹤?
提前感謝!
dt == null僅檢查DataTable是否不爲null。您應該檢查dt.Rows的計數。如果if爲零,則會得到IndexOutOfRangeException –