【问题标题】:create a c# listBox in run time to select multiple choices (that comes from database)在运行时创建一个 c# listBox 以选择多个选项(来自数据库)
【发布时间】:2015-10-01 23:40:55
【问题描述】:

我正在关注这个post

这是一个简单的应用程序,管理员可以在其中准备一份问卷和一份简单的调查,并与在我们网站上注册的任何人分享。

一旦最终用户完成调查,网站管理员(或任何被授权的人)可以分析调查结果和其他任何形式的反馈,如图形或文本。

--但是里面有些东西坏了--

当你添加问题时,你选择问题的类型,所以我做了这门课

  public enum QuestionTypes
    {
        SingleLineTextBox, // will render a textbox 
        MultiLineTextBox, // will render a text area
        YesOrNo, //will render a checkbox
        SingleSelect, //will render a dropdownlist
        MultiSelect //will render a listbox
    }

并将其作为字符串保存在数据库中,但它在运行时以不同的方式呈现(文本框、SingleLineTextBox、YesOrNo 运行良好,但 MultiSelect 和 YesOrNo 不起作用)

此应用程序使用实体框架 - 有一个部分可以添加问题。它看起来像这样:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ddlTypes.Items.Add(QuestionTypes.SingleLineTextBox.ToString());
            ddlTypes.Items.Add(QuestionTypes.MultiLineTextBox.ToString());
            ddlTypes.Items.Add(QuestionTypes.SingleSelect.ToString());
            ddlTypes.Items.Add(QuestionTypes.MultiSelect.ToString());
            ddlTypes.Items.Add(QuestionTypes.YesOrNo.ToString());
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SurveyAppConString context = new SurveyAppConString();
            Question quest = new Question();
            quest.Text = txtTitle.Text.Trim();
            quest.QuestionType = ddlTypes.SelectedItem.Text;
            quest.Options = txtValues.Text.Trim();

            context.AddToQuestions(quest);
            context.SaveChanges();
        }

之后,您可以将任何问题分配给调查,并且有一个页面可以显示所有调查。那里坏了。我想在运行时创建一个复选框并将他的值作为字符串保存在数据库中,并用列表框做同样的事情

这是示例代码(适用于文本框和下拉列表)

    private void PopulateSurvey()
    {
        btnSubmit.Enabled = true;
        List<Question> questions = (from p in context.Questions
                                    join q in context.SurveyQuestions on p.ID equals q.QuestionID
                                    where q.SurveyID == surveyid
                                    select p).ToList();
        Table tbl = new Table();
        tbl.Width = Unit.Percentage(100);
        TableRow tr;
        TableCell tc;
        TextBox txt;
        CheckBox cbk;
        DropDownList ddl;

        foreach (Question q in questions)
        {
            tr = new TableRow();
            tc = new TableCell();
            tc.Width = Unit.Percentage(25);
            tc.Text = q.Text;
            tc.Attributes.Add("id", q.ID.ToString());
            tr.Cells.Add(tc);
            tc = new TableCell();

            if (q.QuestionType.ToLower() == "singlelinetextbox")
            {
                txt = new TextBox();
                txt.ID = "txt_" + q.ID;
                txt.Width = Unit.Percentage(40);
                tc.Controls.Add(txt);
            }

            if (q.QuestionType.ToLower() == "multilinetextbox")
            {
                txt = new TextBox();
                txt.ID = "txt_" + q.ID;
                txt.TextMode = TextBoxMode.MultiLine;
                txt.Width = Unit.Percentage(40);
                tc.Controls.Add(txt);
            }

            if (q.QuestionType.ToLower() == "singleselect")
            {
                ddl = new DropDownList();
                ddl.ID = "ddl_" + q.ID;
                ddl.Width = Unit.Percentage(41);
                if (!string.IsNullOrEmpty(q.Options))
                {
                    string[] values = q.Options.Split(',');
                    foreach (string v in values)
                        ddl.Items.Add(v.Trim());
                }
                tc.Controls.Add(ddl);
            }

            tc.Width = Unit.Percentage(80);
            tr.Cells.Add(tc);
            tbl.Rows.Add(tr);
        }
        pnlSurvey.Controls.Add(tbl);
    }

你可以快速查看完整代码here这是一个数据库图:

注意—— 我在复选框区域工作并添加了类似的代码

我就是这样写代码的

       if (q.QuestionType.ToLower() == "yesorno")
{
    lblyes = new Label();
    lblyes.Text = "yes";
    tc.Controls.Add(lblyes);

     cbk = new CheckBox();
     cbk.ID = "cbk_" + q.ID;
     //cbk.value = "true";
          cbk.Width=Unit.Percentage(41);
                tc.Controls.Add(cbk);

}

 // On Postback|Save
  sres.Response = (ctrc as CheckBox).Checked ? "yes" : "no";

它就这样显示了

效果很好(一个复选框)

制作两个复选框(最好创建一个单选按钮) 我创建并工作得很好

 if (q.QuestionType.ToLower() == "yesorno")//this is the name you create it when add anew question type
{
    lblyes = new Label();
    lblyes.Text = "yes";
    tc.Controls.Add(lblyes);

    rbk = new RadioButton();
    rbk.ID = "rbk_" + q.ID;
    rbk.GroupName = "rbyesno";

    rbk.Width = Unit.Percentage(41);
    tc.Controls.Add(rbk);



    //add another chexbox and label

                lblno = new Label();
                lblno.Text = "no";
                tc.Controls.Add(lblno);

                rbk = new RadioButton();
                rbk.ID = "cbk_1" + q.ID;
                rbk.GroupName = "rbyesno";

                rbk.Width = Unit.Percentage(41);
                tc.Controls.Add(rbk);

}

// On Postback|Save
else if (ctrc is RadioButton)
   {
   //sres.Response = (ctrc as CheckBox).Checked.ToString();
   sres.Response = (ctrc as RadioButton).Checked ? "no" : "yes";
   }

我们检查最后一个单选按钮(在第一个单选按钮之后创建)

---现在我只需要创建一个列表来从表单中选择多个选项并将其作为字符串发送到数据库

--- 当我尝试添加 alistbox 时,coud 添加一个多重选择问题类型到 asurvey

这是代码的 asn-p

 if (q.QuestionType.ToLower() == "MultiSelect")
            {

                lstmulti = new ListBox();
                lstmulti.ID = "lst_" + q.ID;
                lstmulti.Width = Unit.Percentage(41);

                //lstmulti.Items.Add("on");
                //lstmulti.Items.Add("sgsd");
                //lstmulti.Items.Add("thre");


                if (!string.IsNullOrEmpty(q.Options))
                {
                    string[] values = q.Options.Split(',');
                    foreach (string v in values)
                        lstmulti.Items.Add(v.Trim());

                }

                tc.Controls.Add(lstmulti);
            }

在保存中 else if (ctrc 是 ListBox) { //sres.Response = (ctrc as ListBox).SelectionMode.ToString(); sres.Response = (ctrc as ListBox).SelectedValue;

                        }

根本没用

它并没有呈现为 alistbox

//在运行时创建列表 if (q.QuestionType.ToLower() == "MultiSelect") { 列表框 lstmulti = new ListBox(); lstmulti.ID = "lst_" + q.ID; lstmulti.Width = Unit.Percentage(41); lstmulti.Height = Unit.Percentage(100);

        lstmulti.SelectionMode = ListSelectionMode.Multiple;

        //to select multible choices and send to database
        if (lstmulti.SelectionMode == ListSelectionMode.Multiple)
        {
            var selected = new List<string>();

            for (int i = 0; i < lstmulti.Items.Count; i++)
            {
                if (lstmulti.Items[i].Selected)

                    selected.Add(lstmulti.Items[i].Text);

                string selectedItem = lstmulti.Items[i].Text;
                //insert command

                ///it should send the result to databse where the table name is Survey_Response and column is Response                   
                //SurveyAppConString db=new SurveyAppConString();
                //    //db.Survey_Response.Include(m => m.Response) = string.Join(",", selected);     
            }


        }

        if (!string.IsNullOrEmpty(q.Options))
        {
            string[] values = q.Options.Split(',');
            foreach (string v in values)
                lstmulti.Items.Add(v.Trim());

        }

        tc.Controls.Add(lstmulti);
    }

//在保存后

else if (ctrc is ListBox)
                            {
                                //sres.Response = (ctrc as ListBox).SelectionMode.ToString();
                                sres.Response = (ctrc as ListBox).Items.ToString();

                            }

notes :: 我正在使用带有实体框架的 asp.net webform

【问题讨论】:

    标签: javascript c# asp.net webforms linq-to-entities


    【解决方案1】:

    对于列表框,您必须将 SelectionMode 设置为 multiple 并设置要呈现的大小。在回发时,如果 SelectionMode 是多个,那么您将需要循环项目并连接结果。

    if (myListBox.SelectionMode == SelectionMode.Multiple)
    {
        var selected = new List<string>();
        foreach (var item in myListBox.Items)
           if (item.Selected)
                selected.Add(item.Text);
    
        response = string.Join(",", selected);
    }
    

    【讨论】:

    • 感谢您的帮助,尚未渲染。我想首先从数据库中获取文本值以填充列表框,然后将选定的选项保存在数据库中。我根据您的评论更新了主线程中的代码以使代码清晰,所以请检查它@Steve
    【解决方案2】:

    您可以轻松地按照示例添加一个具有“true”值的复选框控件。问题是未选中的复选框不会作为表单值传递,因此如果表单名称不存在于表单帖子中,您可以将其设置为默认“false”,或者您可以在复选框字段后设置隐藏的默认值并使用第一个传递的值

    MVC 中的模型绑定将为您执行此操作 https://stackoverflow.com/a/14731571/60669

    由于脚本只是查看服务器控件,因此更加简单

    if (q.QuestionType.ToLower() == "yesorno")
    {
         var cb = new Checkbox();
         cb.Id = "cb_" + q.id;
         cb.Value = "true;
         // add to table cell
    }
    
    // On Postback|Save
    if (ctrl is Checkbox)
    {
        sres.Result = (ctrl as Checkbox).Checked ? "true" : "false"
    }    
    

    【讨论】:

    • 您的评论非常有帮助,感谢@Steve——因为我是网络开发的新手,所以我会尝试再次解释我想做的事情。我想让 2 个复选框,一个在这里的值等于是,另一个等于否,我想​​将该值保存为普通字符串(是或否),与示例中的下拉列表相同
    • 我做这样的代码 if (q.QuestionType.ToLower() == "yesorno") { lblyes = new Label(); lblyes.Text = "是"; tc.Controls.Add(lblyes); cbk = new CheckBox(); cbk.ID = "cbk_" + q.ID; //cbk.value = "真"; cbk.Width=单位.百分比(41); tc.Controls.Add(cbk); } // 在回发|保存 sres.Response = (ctrc as CheckBox).Checked ? “是”:“否”;它工作得很好(一个复选框)有没有办法添加2个复选框而不是一个(我会试试这个)但我需要在运行时创建一个列表来选择多个选项
    • 如果你想要两个输入 YES|NO 那么你会想要使用一个单选按钮,它只允许一个选择而不是两个可以同时被检查的复选框。只需添加一个 RadioButtonList 并像下拉列表一样添加两个项目,然后查找 SelectedValue
    • 是的,谢谢它与单选按钮配合得很好,但我真的有一个列表框的问题,因为它还没有工作或呈现,我真的不知道为什么,请你检查我的线程更新我可以更详细地解释@Steve
    • 您的单选按钮实现将无法工作,因为它会找到两个控件,真正的单选按钮和假单选按钮 - RadioButton 列表将生成具有单个值但呈现多个项目的单个控件,您不需要手动添加它会根据 ListItem 值和文本为您执行的标签。
    【解决方案3】:

    由于语法错误,列表框未呈现 一般来说,工作代码在这里

            //create list in run time
            if (q.QuestionType == "MultiSelect")
            {
                 lstmulti = new ListBox();
                lstmulti.ID = "lst_" + q.ID;
                lstmulti.Width = Unit.Percentage(41);
                lstmulti.Height = Unit.Percentage(100);
    
                lstmulti.SelectionMode = ListSelectionMode.Multiple;
    
    
    
    
                //to retrive the option values
                if (!string.IsNullOrEmpty(q.Options))
                {
                    string[] values = q.Options.Split(',');
                    foreach (string v in values)
                        lstmulti.Items.Add(v.Trim());
    
                }
    
                tc.Controls.Add(lstmulti);
            }
    
    
    
                tc.Width = Unit.Percentage(80);
                tr.Cells.Add(tc);
                tbl.Rows.Add(tr);
            }
            pnlSurvey.Controls.Add(tbl);
        }
    

    保存中

     else if (ctrc is ListBox)
                                {
                                    var selected = new List<string>();
                                    for (int i = 0; i < lstmulti.Items.Count; i++)
                                    {
    
                                        if (lstmulti.Items[i].Selected)
    
                                            selected.Add(lstmulti.Items[i].Text);
    
                                        string selectedItem = lstmulti.Items[i].Text;
                                        sres.Response = string.Join(",", selected) ;
    
    
                                    }
    
    
    
                                }
                            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2013-04-03
      • 2017-08-08
      • 2014-10-22
      相关资源
      最近更新 更多