Keep your database object local to the methods where they are used. Many of them need to be closed and disposed. using
blocks take care of this for you.
Don't open your connection until directly before the line with an .Execute...
method. There are a limited number of connections available and they should be returned to the pool as quickly as possible.
I had to guess what you login code might look like. I assumed the StudentID is an integer field. Always use parameters to avoid Sql injection. I used .ExecuteScalar()
since we are only expecting a single piece of data, the Faculty associated with the student.
In the loadCandidate
method I used a DataTable
to hold the data because I wasn't sure if a DataReader
could be a DataSource
for a GridView
. In the Select string we use a parameter in the Where clause, the value of which we set in the login.
private string conStr = "Your connection string";
private string facultyID = "";
protected void login()
{
using (MySqlConnection con = new MySqlConnection(conStr))
using (MySqlCommand cmd = new MySqlCommand("Select Faculty From Voter Where StudentID = @ID and Name = @Name;", con))
{
cmd.Parameters.AddWithValue("@ID", (int)txtID.Text);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
con.Open();
facultyID = cmd.ExecuteScalar().ToString();
} //Connection and Command are closed and disposed here.
}
protected void loadCandidate()
{
DataTable dt = null;
using (MySqlConnection con = new MySqlConnection(conStr))
using (MySqlCommand cmd = new MySqlCommand("select studentID ,name from candidate Where Faculty = @FacultyID ", con))
{
cmd.Parameters.AddWithValue("@FacultyID", facultyID);
con.Open();
dt.Load(cmd.ExecuteReader());
} //Connection and Command are closed and disposed here.
GridView1.DataSource = dt;
GridView1.DataBind();
}