Hi I am a fresher in asp.net.
In the below situation i want to display question when the button is clicked. I used for loop. But the problem is i can able to display only the last question and option. But if i use response.write all the 3 question and option are displayed. I have placed my code and output below.
Can any one please help me on this.
In program.cs
protected void Button1_Click1(object sender, EventArgs e)
{
DatabaseDLL.Quiz ObjQuiz = DatabaseDLL.Manager.DisplayQuestions("General Knowledge");
if (IsPostBack)
{
foreach (DatabaseDLL.Question Q in ObjQuiz.GetQuestions())
{
Response.Write(Q.Question1);
Response.Write(Q.Option1);
Response.Write(Q.Option2);
Label1.Text = Q.Question1;
Label2.Text = Q.Option1;
Label3.Text = Q.Option2;
}
}
}
In the dll manager class:
public static Quiz DisplayQuestions(string category)
{
Quiz ObjQuiz = new Quiz();
try
{
Conn = new SqlConnection("Data Source=HDCHARTOMR1213\\SQLEXPRESS;Initial Catalog=UserDetails;Integrated Security=SSPI");
Conn.Open();
SqlCommand Cmd = new SqlCommand("QuizQuestions", Conn);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("@Category", category);
SqlDataReader reader = Cmd.ExecuteReader();
while (reader.Read())
{
Question ObjQuestion = new Question(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString());
ObjQuiz.AddQuestion(ObjQuestion);
}
reader.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (Conn != null)
{
Conn.Close();
}
}
return ObjQuiz;
}
Question Class:
public class Question
{
public string Option1 { get; private set; }
public string Option2 { get; private set; }
public string Question1 { get; private set; }
public string Category { get; private set; }
public Question(string Question1, string Option1, string Option2, string Category)
{
this.Question1 = Question1;
this.Option1 = Option1;
this.Option2 = Option2;
this.Category = Category;
}
}
Quiz Class:
public class Quiz
{
public List<question> ObjQuestion = new List<question>();
public void AddQuestion(Question NewQuestion)
{
ObjQuestion.Add(NewQuestion);
}
public List<question> GetQuestions()
{
return ObjQuestion;
}
public Quiz()
{
}
}
Output:
After Button click i get the following output below:
//for response.write
Who is the Father of our Nation
Mahathma Gandhi
Jawaharlal Nehru
What is our National Animal
Lion
Tiger
What is our National Flower
Lotus
Rose
//for the label only last Question and options are displayed
What is our National Flower //label1
Lotus //label2
Rose //label3
Thank You!!