从数据库添加动态多视图

问题描述 投票:0回答:1

我尝试制作一个检查系统,以便管理员对问题和选择以及答案我不会在用户方面显示问题,并在多视图中选择每个视图都有一个问题和3个单选按钮每个选择一个 我的代码只给我带来了表格中的最后一个问题

    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT * FROM exam WHERE exam_name='" + Request.QueryString["examid"] + "'";
    cmd.ExecuteNonQuery();
    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);
    d1.DataSource = dt;
    d1.DataBind();

    View view = new View();
    Label label = new Label();
    RadioButton RadioButtonA = new RadioButton();
    RadioButton RadioButtonB = new RadioButton();
    RadioButton RadioButtonC = new RadioButton();
    foreach (DataRow dr in dt.Rows)
    {
        label.Text = dr["qustion"].ToString();
        RadioButtonA.Text= dr["cha"].ToString();
        RadioButtonB.Text = dr["chb"].ToString();
        RadioButtonC.Text = dr["chc"].ToString();
        view.Controls.Add(label);
        view.Controls.Add(RadioButtonA);
        view.Controls.Add(RadioButtonB);
        view.Controls.Add(RadioButtonC);
        m1.Views.Add(view);
    }
    if (!IsPostBack)
    {
        m1.ActiveViewIndex = 1;
    }

    con.Close();
c# asp.net sql-server
1个回答
0
投票

您可以在循环外创建实例,以便每次程序进入循环时。它只重写现有控件的文本而不是创建新的控件。这就是为什么它似乎只剩下最后一个问题了。

你想要的应该是什么样的

View view;
Label label;
RadioButton RadioButtonA, RadioButtonB, RadioButtonC;
foreach (DataRow dr in dt.Rows)
{
    view = new View();
    label = new Label();
    RadioButtonA = new RadioButton();
    RadioButtonB = new RadioButton();
    RadioButtonC = new RadioButton();

    label.Text = dr["qustion"].ToString();
    RadioButtonA.Text= dr["cha"].ToString();
    RadioButtonB.Text = dr["chb"].ToString();
    RadioButtonC.Text = dr["chc"].ToString();
    view.Controls.Add(label);
    view.Controls.Add(RadioButtonA);
    view.Controls.Add(RadioButtonB);
    view.Controls.Add(RadioButtonC);
    m1.Views.Add(view);
}
© www.soinside.com 2019 - 2024. All rights reserved.