简体   繁体   中英

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 )

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

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(); sres.Response = (ctrc as ListBox).SelectedValue;

                        }

it didn't work at all 在此处输入图片说明

and it didn't render too as alistbox

//create list in run time if (q.QuestionType.ToLower() == "MultiSelect") { ListBox 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);
    }

//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

You can easily follow the example and add a checkbox control with a "true" value. 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

Model binding in MVC will do this for you 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. On postback if the SelectionMode is multiple then you will need to loop the items and concatenate the results.

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


                                }



                            }
                        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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