简体   繁体   English

在运行时创建ac#listBox以选择多个选项(来自数据库)

[英]create a c# listBox in run time to select multiple choices (that comes from database)

I'm following this post 我正在关注这篇文章

This is a simple application where administrators can prepare a questionnaire and prepare a simple survey and share it with whoever registered on our website. 这是一个简单的应用程序,管理员可以准备问卷并准备简单的调查并与我们网站上注册的任何人共享。

Once the survey is completed by end users, the web site administrator (or whoever is authorized) can analyze the survey results and other feedback in any form like graphical or textual. 最终用户完成调查后,网站管理员(或授权的任何人)都可以以任何形式(例如图形或文本)分析调查结果和其他反馈。

-- but there are some thing broken in it-- -但是里面有些东西坏了-

when you add a question you choose the type of question, so I made this class 当您添加问题时,您可以选择问题的类型,因此我开设了此类

  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
    }

and saved it in the database as a string but it renders in runtime in a different way ( the textbox ,SingleLineTextBox ,YesOrNo work well but MultiSelect and YesOrNo do not work ) 并将其保存为字符串,但是以不同的方式在运行时呈现(文本框,SingleLineTextBox,YesOrNo可以正常工作,但是MultiSelect和YesOrNo不能工作)

This application uses entity framework - there is a section to add a question. 此应用程序使用实体框架-有一节添加问题。 It looks like this: 看起来像这样:

    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();
        }

在此处输入图片说明

After that you can assign any question to survey and there's a page to display all surveys. 之后,您可以将任何问题分配给调查,然后会有一个页面显示所有调查。 It is broken there. 它在那儿坏了。 I want to create a checkbox in run time and take his value as a string and save it in database and make the same thing with a listbox too 我想在运行时创建一个复选框,并将其值作为字符串保存在数据库中,并使用列表框进行相同操作

This is sample code ( works for textboxes and dropdownlist) 这是示例代码(适用于文本框和下拉列表)

    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);
    }

You can quickly check the full code here and this is a database diagram: 您可以在此处快速检查完整的代码,这是一个数据库图:

在此处输入图片说明

note -- i worked in checkboxes area and added the code like that 注意-我在复选框区域工作并添加了类似的代码

i do the code like that 我这样做的代码

       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";

and it showed like that 它显示像 在此处输入图片说明

it worked fine ( one checkbox ) 它工作正常(一个复选框)

to make two checkbox ( it's better to create aradiobutton) i created and worked fine 创建两个复选框(最好创建一个单选按钮)

 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";
   }

We check on last radiobutton ( as created after the first one) 我们检查最后一个单选按钮(在第一个按钮之后创建) 在此处输入图片说明

--- now i just need to create a list to select multiple choices from form and send it as a string to database ---现在我只需要创建一个列表即可从表单中选择多个选项并将其作为字符串发送到数据库

--- when i try to add alistbox so colud add a multible select quesion type to asurvey ---当我尝试添加列表框时,请colud添加一个多重选择查询类型以进行查询

this is asnippet of code 这是代码的摘要

 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);
            }

in save else if (ctrc is ListBox) { //sres.Response = (ctrc as ListBox).SelectionMode.ToString(); 在保存其他情况下(ctrc是ListBox){//sres.Response =(ctrc作为ListBox).SelectionMode.ToString(); sres.Response = (ctrc as ListBox).SelectedValue; sres.Response =(ctrc作为ListBox).SelectedValue;

                        }

it didn't work at all 根本没有用 在此处输入图片说明

and it didn't render too as alistbox 它也没有呈现为alistbox

//create list in run time if (q.QuestionType.ToLower() == "MultiSelect") { ListBox lstmulti = new ListBox(); //在运行时创建列表,如果(q.QuestionType.ToLower()==“ MultiSelect”){ListBox lstmulti = new ListBox(); lstmulti.ID = "lst_" + q.ID; lstmulti.ID =“ lst_” + q.ID; lstmulti.Width = Unit.Percentage(41); lstmulti.Width = Unit.Percentage(41); lstmulti.Height = Unit.Percentage(100); 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);
    }

//in post-save //保存后

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

                            }

notes :: i'm using asp.net webform with entity framwork notes ::我正在将asp.net Webform与实体框架一起使用

You can easily follow the example and add a checkbox control with a "true" value. 您可以轻松地遵循该示例,并添加具有“ true”值的复选框控件。 The issue is that unchecked checkboxes are not passed as form values so you could either set it to a default "false" if the form name does not exist in the form post, or you can set a hidden default value after the checkbox field and use the first passed value 问题是未选中的复选框不会作为表单值传递,因此如果表单名称不存在于表单发布中,则可以将其设置为默认的“ false”,也可以在复选框字段之后设置隐藏的默认值并使用第一个通过的值

Model binding in MVC will do this for you https://stackoverflow.com/a/14731571/60669 MVC中的模型绑定将为您做到这一点https://stackoverflow.com/a/14731571/60669

Since the script is just looking at the Server controls its even simpler 由于脚本只是查看服务器控件,因此它甚至更简单

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"
}    

For the listbox you'll have to set the SelectionMode to multiple and set the size to render. 对于列表框,您必须将SelectionMode设置为multiple并将大小设置为可渲染。 On postback if the SelectionMode is multiple then you will need to loop the items and concatenate the results. 在回发时,如果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);
}

the listbox didn't render because of syntax error in general the worked code are here 由于语法错误,列表框未呈现,通常工作的代码在这里

        //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);
    }

in save 在保存

 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) ;


                                }



                            }
                        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM