我想返回存储在数据库中的最后一条记录,并希望将返回值实例化为ReligionCaste类的成员pID, 但我有标题错误。
我的数据库功能是
public int LastEnteredRecord()
{
int lastId=0;
dbConnection = new SqlConnection(connectionString);
try //If error in connection opening, throws it.
{
dbConnection.Open();
command.Connection = dbConnection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "dbo.LastRecordEntered";
try //if error in query execution, throws it.
{
lastId= Convert.ToInt32 ( command.ExecuteScalar());
// MessageBox.Show("Record Entered with ID:"+lastId .ToString ());
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
dbConnection.Close();
dbConnection.Dispose();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
return lastId;
}
我想将该返回值分配给代码为
的类class ReligionCaste
{
//public int religion_ID, caste_ID;
public String religion, sect, caste, subCaste;
public int pID;
DatabaseHandler.DBCntrlr dbObj = new DatabaseHandler.DBCntrlr();
pID = dbObj.LastEnteredRecord();
}
但它给出了上述错误。
答案 0 :(得分:5)
在语法无效时,您需要一个构造函数为pId赋值。例如:
class ReligionCaste
{
public ReligionCaste()
{
pID = dbObj.LastEnteredRecord();
}
//public int religion_ID, caste_ID;
public String religion, sect, caste, subCaste;
public int pID;
DatabaseHandler.DBCntrlr dbObj = new DatabaseHandler.DBCntrlr();
}
答案 1 :(得分:2)
class ReligionCaste
{
//public int religion_ID, caste_ID;
public String religion, sect, caste, subCaste;
public int pID;
private DatabaseHandler.DBCntrlr dbObj;
public ReligionCaste()
{
dbObj = new DatabaseHandler.DBCntrlr();
pID = dbObj.LastEnteredRecord();
}
}