Click here to Skip to main content
15,949,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I m trying to make a online exam page in website,


my code is in .cs is:

C#
public static SqlConnection sqlconn;
    protected string PostBackStr;
    int startid = 1;//Here specify your starting id of Questions table. So that it will display questions from id starting from this value
    int endid = 4;//Here specify your ending id of Questions table. So that it will display questions which has id below this value
    int totalnoofquestions = 4;//Here change the number of questions you want to display.
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["cnnstring"].ToString());
        PostBackStr = Page.ClientScript.GetPostBackEventReference(this, "time");

        if (IsPostBack)
        {
            string eventArg = Request["__EVENTARGUMENT"];
            if (eventArg == "time")
            {
                getNextQuestion();
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Visible = false;
        txtName.Visible = false;
        Button1.Visible = false;
        Panel1.Visible = true;
        lblName.Text = "Name : " + txtName.Text;
        int score = Convert.ToInt32(txtScore.Text);
        lblScore.Text = "Score : " + Convert.ToString(score);
        Session["counter"] = "1";
        Random rnd = new Random();
        int i = rnd.Next(startid ,endid+1 );
        getQuestion(i);
        ArrayList al = new ArrayList();
        al.Add(i.ToString());
        Session["ids"] = al;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        getNextQuestion();
    }
    protected void Finish_Click(object sender, EventArgs e)
    {
        if (Session["Answer"].ToString() == RblOption.SelectedIndex.ToString())
        {
            int score = Convert.ToInt32(txtScore.Text) + 1;// 1 for mark for each question
            txtScore.Text = score.ToString();
            lblScore.Text = "Score : " + Convert.ToString(score);
        }
        lblResult.Text = "Thank you for test our application. Your Score is : " + txtScore.Text;
        lblResult.Visible = true;
        Panel2.Visible = false;
    }
    public void getQuestion(int no)
    {
        
        string str = "select * from Questions where id=" + no + "";
        SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
        DataSet ds2 = new DataSet();
        da2.Fill(ds2, "Question");
        if (ds2.Tables[0].Rows.Count > 0)
        {
            DataRow dtr;
            int i = 0;
            while (i < ds2.Tables[0].Rows.Count)
            {
                dtr = ds2.Tables[0].Rows[i];
                Session["Answer"] = Convert.ToString(Convert.ToInt32(dtr["Correct"].ToString()) - 1);
                lblQuestion.Text = "Q." + Session["counter"].ToString() + "  " + dtr["Question"].ToString();
                RblOption.ClearSelection();
                RblOption.Items.Clear();
                RblOption.Items.Add(dtr["Option1"].ToString());
                RblOption.Items.Add(dtr["Option2"].ToString());
                RblOption.Items.Add(dtr["Option3"].ToString());
                RblOption.Items.Add(dtr["Option4"].ToString());
                i++;
            }
        }
    }
    public void getNextQuestion()
    {
        if (Convert.ToInt32(Session["counter"].ToString()) < totalnoofquestions)
        {
            if (RblOption.SelectedIndex >= 0)
            {
                if (Session["Answer"].ToString() == RblOption.SelectedIndex.ToString())
                {
                    int score = Convert.ToInt32(txtScore.Text) + 1;// 1 for mark for each question
                    txtScore.Text = score.ToString();
                    lblScore.Text = "Score : " + Convert.ToString(score);
                }
            }
            Random rnd = new Random();
            int i = rnd.Next(startid ,endid );
            ArrayList al = (ArrayList)Session["ids"];
            if (!al.Contains(i.ToString()))
            {
                al.Add(i.ToString());
            }
            else
            {
                while (al.Contains(i.ToString()))
                {
                    i = rnd.Next(startid, endid + 1);

                    if (al.Count == totalnoofquestions - 1 && !al.Contains(i.ToString()))
                    {
                        Button2.Visible = false;
                        Finish.Visible = true;
                        break;
                    }
                    else if (al.Count > endid + 1)
                    {
                        break;
                    }

                }
                if (!al.Contains(i.ToString()))
                {
                    al.Add(i.ToString());
                }
            }
            if (al.Count == totalnoofquestions)
            {
                Button2.Visible = false;
                Finish.Visible = true;
            }
            Session["ids"] = al;
            Session["counter"] = Convert.ToString(Convert.ToInt32(Session["counter"].ToString()) + 1);
            getQuestion(i);
            
            

        }
        else
        {
            Panel2.Visible = false;
            //code for displaying after completting the exam, if you want to show the result then you can code here.
        }
    }
    public void ConnectionOpen()
    {
        try
        {
            if (sqlconn.State == ConnectionState.Closed) { sqlconn.Open(); }
        }
        catch (SqlException ex)
        { }
        catch (SystemException sex)
        { }
    }
    public void ConnectionClose()
    {
        try
        {
            if (sqlconn.State != ConnectionState.Closed) { sqlconn.Close(); }
        }
        catch (SqlException ex)
        { }
        catch (SystemException exs)
        { }
    }
}

but it gives the error
C#
Server Error in '/Online Exam' Application.
Fill: SelectCommand.Connection property has not been initialized.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.

Source Error:

Line 75:         SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
Line 76:         DataSet ds2 = new DataSet();
Line 77:         da2.Fill(ds2, "Question");
Line 78:         if (ds2.Tables[0].Rows.Count > 0)
Line 79:         {


Source File: c:\Documents and Settings\DW\Desktop\New Folder\Online Exam\Default.aspx.cs    Line: 77

Stack Trace:

[InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.]
   System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method) +4995530
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +76
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +319
   System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable) +92
   _Default.getQuestion(Int32 no) in c:\Documents and Settings\DW\Desktop\New Folder\Online Exam\Default.aspx.cs:77
   _Default.Button1_Click(Object sender, EventArgs e) in c:\Documents and Settings\DW\Desktop\New Folder\Online Exam\Default.aspx.cs:50
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1


how to solve this problem....
Posted
Updated 27-May-12 20:57pm
v2

Fill: SelectCommand.Connection property has not been initialized
Error tells exactly what you need to do.

You failed/missed opening the SQL Connection. Open it before using the select command for getting the question.
 
Share this answer
 
Comments
aarohi verma 28-May-12 4:25am    
thank you for suggestion.its help me loat.
Sandeep Mewara 28-May-12 4:36am    
Good to know.
aarohi verma 28-May-12 6:53am    
how to mark it as solve?
why you are getting this problem means you are not assigned any connection string to the Sqlconnection sqlcnn object simply you declared it globally but not assigned any value to that
try like this

public SqlConnection sqlconn=SqlConnection(ConfigurationManager.AppSettings["cnnstring"].ToString());
 
Share this answer
 
v2
Comments
aarohi verma 28-May-12 4:25am    
thank you
vangapally Naveen Kumar 28-May-12 4:35am    
Welcome............................

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900