Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried displaying but it seems to have a problem.
Please help me find out the problem.

What I have tried:

C#
public void getQuestionOne()
        {
            string MYDBConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYDBConnection"].ConnectionString;
            SqlConnection con = new SqlConnection(MYDBConnectionString);

            con.Open();
            string sql = "select question1, question2 from Customer where username=@UserID";
            SqlCommand cmd = new SqlCommand(sql, con);
            try
            {

                using (SqlDataReader read = cmd.ExecuteReader())
                {
                    while (read.Read())
                    {
                        lblqnsOne.Text = (read["question1"].ToString());
                        lblqnsTwo.Text = (read["question2"].ToString());

                    }
                }
            }
            finally
            {
                con.Close();
            }
        }
Posted
Updated 29-Jul-18 7:07am
v2

1 solution

One obvious reason why your code isn't working because you haven't assigned the parameter @UserID in your SQL query. To fix that, you can do something like this:

C#
private void GetQuestionOne(int userID){
     	String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            using(SqlConnection con = new SqlConnection(strConnString)){
            	using(SqlCommand cmd = new SqlCommand("SELECT question1, question2 from Customer where username=@UserID", con)){
			        con.Open();
                    cmd.Parameters.AddWithValue("@UserID", userID);
            		using (SqlDataReader read = cmd.ExecuteReader())
                        {
                            while (read.Read())
                            {
                                lblqnsOne.Text = read["question1"].ToString();
                                lblqnsTwo.Text = read["question2"].ToString();

                            }
                        }
	    	}
	    }
}


Tip: Make it a habit to put objects that eat resources such as SqlConnection, SqlCommand, SqlDataAdapter, SqlDataReader within a using statement to ensure that objects will be properly disposed and closed after they are used.
 
Share this answer
 

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