-1

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

enter image description here

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:

enter image description here

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 enter image description here

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) enter image description here

--- 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 enter image description here

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

user4833581
  • 107
  • 1
  • 3
  • 14

3 Answers3

1

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"
}    
Community
  • 1
  • 1
Steve
  • 1,995
  • 2
  • 16
  • 25
  • your comment is extremely helpful ,thanks @Steve -- as i'm new to web development so i'll try to explain what i want to do again . i want to make 2 checkboxs one here value equal to yes and another one equal to no and i want to save the value as a normal string ( yes or no) the same happen with dropdownlist as in example – user4833581 Oct 02 '15 at 02:19
  • 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"; it worked fine ( one checkbox ) is there any way to add 2 checkboxs not one ( i'll try this) but i need to create alist in runtime to select multible choices – user4833581 Oct 02 '15 at 02:40
  • 1
    If you want two inputs for YES|NO then you would want to use a radio button that will only allow one choice vs two checkboxes that can both be chedked. Just add a RadioButtonList and add two items just like the droplist and then look for the SelectedValue – Steve Oct 02 '15 at 15:56
  • 1
    yeah thanks it worked well with radio buttons ,but i really had aproblem with a listbox as it didn't work or render yet and i really didn't know why ,could you please check my thread update as i can explain in more details @Steve – user4833581 Oct 03 '15 at 01:32
  • 1
    your radiobutton implementation will not work as it will find two controls, the true radio button and the false radio button - the RadioButton list will result in a single control with a single value but render multiple items, you wont need to manually add the label it will do it for you based on the ListItem value and text. – Steve Oct 03 '15 at 04:15
  • i didn't get what you mean ( as i'm a newbie some how in web development) the radiobutton it works well but in some logig ( the two radiobutton take the same name ) so he act with the 2 radiobutton as the only one and now if he check the first one labeled with yes it already reads the he didn't check and send in database ( yes value as i want ) – user4833581 Oct 03 '15 at 04:22
  • sres.Response = (ctrc as RadioButton).Checked ? "no" : "yes"; as in this code and i tested it and work fine – user4833581 Oct 03 '15 at 04:23
  • but my problem now in a lisebox ( i try the code logic and work ) but in this context ,the result was no ... it did't render as alistbox yet @Steve – user4833581 Oct 03 '15 at 04:24
  • Because you are adding two controls, the code from the link you provided would actually create a responses for each radio button found, [x] Yes [ ] No would result in a [Response=True],[Response=False]. [ ] Yes [x] No would result in a [Response=False],[Response=True]. Try Debugging and look at the question responses or look at the database – Steve Oct 03 '15 at 04:31
1

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);
}
Steve
  • 1,995
  • 2
  • 16
  • 25
  • thanks for your help, it didn't render yet . i want in first get the text value from database to fill the listbox then work in saving the selected choices in database .. i updated the code in the main thread based in your comment to make the code clear ,so please check it @Steve – user4833581 Oct 03 '15 at 06:25
0

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


                                }



                            }
                        }
user4833581
  • 107
  • 1
  • 3
  • 14