I am writting a programme, which imports data from data base. I want to place all these tables in my own object propeties. All these DataTable properties are filled until Base examBase = Base()
is beeing executed, but after this line, the exam.Base.Tests
doesnt's exist anymore. What causes the problem?
class Base
{
MySqlConnection myConnection;
MySqlDataAdapter testsDataAdapter;
DataTable testsDataTable;
MySqlDataAdapter questionsDataAdapter;
DataTable questionsDataTable;
MySqlDataAdapter answersDataAdapter;
DataTable answersDataTable;
public Base()
{
string myConnectionString = "Database=Exams;Data Source=localhost;User Id=root;Password=";
myConnection = new MySqlConnection(myConnectionString);
myConnection.Open();
GetTests();
GetQuestions();
GetAnswers();
}
private void GetTests()
{
string testQuery = "SELECT * FROM tests";
testsDataAdapter = new MySqlDataAdapter(testQuery, myConnection);
testsDataTable = new DataTable();
testsDataAdapter.Fill(testsDataTable);
testsDataTable.PrimaryKey = new DataColumn[] { testsDataTable.Columns["TestID"] };
this.Tests = testsDataTable;
}
private void GetQuestions()
{
string questionQuery = "SELECT * FROM questions";
questionsDataAdapter = new MySqlDataAdapter(questionQuery, myConnection);
questionsDataTable = new DataTable();
questionsDataAdapter.Fill(questionsDataTable);
this.Questions = questionsDataTable;
}
private void GetAnswers()
{
string answerQuery = "SELECT * FROM answers";
answersDataAdapter = new MySqlDataAdapter(answerQuery, myConnection);
answersDataTable = new DataTable();
answersDataAdapter.Fill(answersDataTable);
this.Answers = answersDataTable;
}
public DataTable Tests { get; set; }
public DataTable Questions { get; set; }
public DataTable Answers { get; set; }
}
and the exception is firstly seen in GetName() method:
class Test
{
Base examBase;
private List<Question> questions;
public Test(int testID)
{
examBase = new Base();
this.TestID = testID;
GetName();
GetDescription();
GetAuthor();
GetQuestions();
}
private void GetName()
{
this.Name = examBase.Tests.Rows.Find(this.TestID)["Name"].ToString();
}
edit
Ok, the object examBase.Tests
exists, but there's something with whis Find()
method. In my base, in the table "Tests" I have a primary key (column TestID), but I get the KeyMissing exception. Meybe I use this Find()
incorrectly?