By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,208 Members | 1,592 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,208 IT Pros & Developers. It's quick & easy.

Can not access dynamic Radiobuttonlist

P: 5
Hi everyone I'm new to this site and the world of ASP.Net C# programming. I have been learning controls and integrating them with a SQL database. So far I have been able to move along and understand static controls. However I would like to move on to attempt to create some dynamic controls. So I set out to work with a radiobuttonlist questionnaire. I have a database and in that DB I have 2 tables one which holds the questions and the other with the possible choices. In the following code I am able to retrieve and display the format or the questions and choices in a radiobuttonlist in a browser. In my submit event I have a for loop which in my static examples I was able to traverse all of the controls I was interested in. However in this new project I can not access the "radio" instance I created. Here is the code in C#.
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;
  10. using System.Data.SqlClient;
  11. using System.Text;
  12.  
  13.  
  14. public partial class _Default : System.Web.UI.Page 
  15. {
  16.     protected void Page_Load(object sender, EventArgs e)
  17.     {
  18.  
  19.  
  20.         SqlConnection thisconnection = new SqlConnection("server=localhost;" + "database=Quest;Trusted_Connection=Yes");
  21.         thisconnection.Open();
  22.         SqlCommand thisCommand = thisconnection.CreateCommand();
  23.         thisCommand.CommandText = "select * from Questions";
  24.         SqlDataReader thisreader = thisCommand.ExecuteReader();
  25.  
  26.         int i = 1;
  27.         while (thisreader.Read())
  28.         {
  29.             TableRow tr = new TableRow();
  30.             // Create column 1
  31.             TableCell td1 = new TableCell();
  32.             // Create a label control dynamically
  33.             Label _label = new Label();
  34.             _label.ID = "lbl" + i.ToString();
  35.             _label.Text = thisreader["Quest_question"].ToString();
  36.             // Add control to the table cell
  37.             td1.Controls.Add(_label);
  38.             tr.Cells.Add(td1);
  39.             Table1.Rows.Add(tr);
  40.  
  41.             SqlConnection conn = new SqlConnection("server=localhost;" + "database=Quest;Trusted_Connection=Yes");
  42.             conn.Open();
  43.             SqlCommand cmd = conn.CreateCommand();
  44.             cmd.CommandText = "select * from Question_type where Type_Question=" + thisreader["Quest_Answer_Type"].ToString();
  45.             SqlDataReader reader = cmd.ExecuteReader();
  46.  
  47.             RadioButtonList radio = new RadioButtonList();
  48.  
  49.  
  50.             radio.ID = "radio_" + thisreader["Quest_ID"].ToString();
  51.             radio.
  52.  
  53.             while (reader.Read())
  54.             {
  55.                 string t;
  56.                 string v;
  57.                 t=reader["Type_Text"].ToString();
  58.                 v=reader["Type_Question"].ToString();
  59.  
  60.                 radio.Items.Add(new ListItem(t,v)); 
  61.             }
  62.  
  63.             //radio.DataBind();
  64.  
  65.             TableRow tr2 = new TableRow();
  66.             // Create column 1
  67.             TableCell td2 = new TableCell();
  68.             TableCell td3 = new TableCell();
  69.             RequiredFieldValidator validate = new RequiredFieldValidator();
  70.             validate.ControlToValidate= radio.ID;
  71.             validate.ErrorMessage = "Please fill out the below question.";
  72.             td2.Controls.Add(radio);
  73.             td3.Controls.Add(validate);
  74.             tr2.Cells.Add(td2);
  75.             tr2.Cells.Add(td3);
  76.             Table1.Rows.Add(tr2);
  77.  
  78.             reader.Close();
  79.             i++; 
  80.         }
  81.         thisreader.Close();
  82.  
  83.  
  84.     }
  85.  
  86.     protected void Button1_Click(object sender, EventArgs e)
  87.     {
  88.         //IerateControls(this);
  89.  
  90.         if (Page.IsValid)
  91.         {
  92.             Response.Write("<h2>Congratulations, registration succeded!</h2>");
  93.  
  94.             foreach (Control c in this.form1.Controls) 
  95.             {
  96.                 if (c is RadioButtonList)
  97.                 {
  98.                     Response.Write(((RadioButtonList)c).SelectedValue + "<br/>");
  99.                 }
  100.             }
  101.  
  102.  
  103.         }
  104.  
  105.         }
  106.     }
  107.  
aspx
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml" >
  6. <head runat="server">
  7.     <title>Untitled Page</title>
  8. </head>
  9. <body>
  10.     <form id="form1" runat="server">
  11.     <div>
  12.         &nbsp;&nbsp;<asp:Table ID="Table1" runat="server">
  13.         </asp:Table>
  14.     </div>
  15.         <br />
  16.  
  17.         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
  18.  
  19.         <br />
  20.  
  21.     </form>
  22. </body>
  23. </html>
Feb 19 '09 #1
Share this Question
Share on Google+
13 Replies


Frinavale
Expert Mod 5K+
P: 9,731
Ok there are a couple of things that you should probably look into.

The first thing is that you are not properly creating your dynamic controls. Please check out this article on how to use dynamic controls in ASP.NET.

The other thing, which is probably more important, is that the RadioButtonList doesn't have to be dynamically created. Only the data within the RadioButtonList (the list items) are dynamic since they are created based on what you retrieve from the database.

What you need to do is grab the data from the database and dynamically create ListItems for your RadioButtonList.

Please look into how to use the RadioButtonList Control.
Feb 19 '09 #2

P: 5
Hi everyone. I am currently trying to do my best to learn ASP.NET /C#. I am working on trying to understand dynamic controls,post backs, and view states. I have read so many articles and I can not get past what seems to be a very simple problem. Here is the scenario. A user picks a value from the drop down list. Once the user picks an item, Im assuming the autopostback=true enables the OnTextChanged event to be fired were I create two dynamic controls 1 radiobuttonlist and 1 label. The user checks a radio value and the submit button is fired. On this event im trying to findcontrol and output to the screen. In reality I want to capture the result and store it in a DB. However when I try and find the radio_1 control on submission I am not able to find the control and out put it to the screen. On the other hand if i look for "dropdownlist 1" I can locate the static control with out any problems. I believe this issue is realated to viewstate and postbacks but i cant find any real examples. This kind of scenerio seems it would be a very common senerio in page development yet there is really no good source of examples. Can anyone please help me understand what needs to be added to the code to make this work? Thank you in advance. The code is as follows.
Expand|Select|Wrap|Line Numbers
  1. <html xmlns="http://www.w3.org/1999/xhtml" >
  2. <head runat="server">
  3.     <title>Untitled Page</title>
  4. </head>
  5. <body>
  6.     <form id="form1" runat="server">
  7.  
  8.     <div>
  9.         <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="QaQuestions"
  10.             DataTextField="Role_Name" DataValueField="Role_ID" OnTextChanged="get_question">
  11.         </asp:DropDownList><asp:SqlDataSource ID="QaQuestions" runat="server" ConnectionString="<%$ ConnectionStrings:QAquestionConnectionString %>"
  12.             SelectCommand="SELECT [Role_Name], [Role_ID] FROM [Role]"></asp:SqlDataSource>
  13.  
  14.         <asp:Panel ID="Panel1" runat="server" Height="50px" Width="500px">
  15.         </asp:Panel>
  16.         <asp:button ID="Button1" runat="server" text="Submit" OnClick="Button1_Click" />
  17.         </div>
  18.     </form>
  19. </body>
  20.  
  21. </html>


The c# code


Expand|Select|Wrap|Line Numbers
  1. protected void Page_Load(object sender, EventArgs e)
  2.     {
  3.  
  4.     }
  5.  
  6.     protected void get_question(object sender, EventArgs e)
  7.     {
  8.         Label question = new Label();
  9.         question.Text = "how do you like your job?";
  10.         Panel1.Controls.Add(question);
  11.  
  12.         RadioButtonList radio = new RadioButtonList();
  13.         radio.ID = "radio_1";
  14.         radio.RepeatDirection = RepeatDirection.Horizontal;
  15.         radio.Items.Add(new ListItem("Yes","1"));
  16.         radio.Items.Add(new ListItem("No","2"));
  17.         radio.Items.Add(new ListItem("N/A","3"));
  18.  
  19.         Panel1.Controls.Add(radio);
  20.     }
  21.  
  22.  
  23.    protected void  Button1_Click(object sender, EventArgs e)
  24. {
  25.     // Find control on page.
  26.     Control myControl1 = FindControl("radio_1");
  27.     if (myControl1 != null)
  28.     {
  29.         // Get control's parent.
  30.         Control myControl2 = myControl1.Parent;
  31.  
  32.         Response.Write("Parent of the text box is : " + myControl2.ID);
  33.     }
  34.     else
  35.     {
  36.         Response.Write("Control not found");
  37.     }
Feb 25 '09 #3

Frinavale
Expert Mod 5K+
P: 9,731
@tommymo
Your assumption is incorrect.
The SelectedIndexChanged event occurs when the selected index changes.

@tommymo
They click the submit button after the chose something in the RadioButtonList right?

@tommymo
Sorry, what?
I don't understand.


Why do you have to dynamically create the controls?
Why can't the be part of the page?
Just change their properties (visible, text and other properties) when you need to use them.

If you are really keen on learning how to use dynamic controls in asp.net please check out this quick overview on how to use dynamic controls in ASP.NET.

I don't think you need to dynamically create the controls though.
I think you just need to put them on the page and set their properties accordingly.


For example, add a Label and a RadioButtonList to your asp:
Expand|Select|Wrap|Line Numbers
  1. <html xmlns="http://www.w3.org/1999/xhtml" >
  2. <head runat="server">
  3.     <title>Untitled Page</title>
  4. </head>
  5. <body>
  6.     <form id="form1" runat="server">
  7.  
  8.     <div>
  9.         <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="QaQuestions"
  10.             DataTextField="Role_Name" DataValueField="Role_ID" OnTextChanged="get_question">
  11.         </asp:DropDownList><asp:SqlDataSource ID="QaQuestions" runat="server" ConnectionString="<%$ ConnectionStrings:QAquestionConnectionString %>"
  12.             SelectCommand="SELECT [Role_Name], [Role_ID] FROM [Role]"></asp:SqlDataSource>
  13.  
  14.         <asp:Panel ID="Panel1" runat="server" Height="50px" Width="500px">
  15.             <asp:Label id="question" runat="server" Visible="false"></asp:Label>
  16.             <asp:RadioButtonList id="radio_1" runat="server" Visible="false"></asp:RadioButtonList>
  17.         </asp:Panel>
  18.         <asp:button ID="Button1" runat="server" text="Submit" OnClick="Button1_Click" />
  19.         </div>
  20.     </form>
  21. </body>
  22.  
  23. </html>
Then you could dynamically set the content of the controls in your get_questions method by:
Expand|Select|Wrap|Line Numbers
  1.   protected void get_question(object sender, EventArgs e)
  2.     {
  3.  
  4.         question.Text = "how do you like your job?";
  5.         question.Visible = true;
  6.  
  7.         radio_1.RepeatDirection = RepeatDirection.Horizontal;
  8.         radio_1.Items.Add(new ListItem("Yes","1"));
  9.         radio_1.Items.Add(new ListItem("No","2"));
  10.         radio_1.Items.Add(new ListItem("N/A","3"));
  11.         radio_1.Visible = true;
  12.     }
Feb 25 '09 #4

P: 5
I need the controls to be dynamic because eventually create them from a question bank in a DB. I need to create a questionnaire with over 50 questions based on a user role. This will be to cumbersome to create static controls. I have tried to look at your tutorial but can apply it to my problem. Why is my assumption incorrect the event is on text change not index?
Feb 25 '09 #5

Frinavale
Expert Mod 5K+
P: 9,731
@tommymo
Ah, I understand now.

It might be easier to use a List of RadioButtonList rather than an array for your solution. You're going to have to use the AddHandler method to link these controls to methods that handle each event.

@tommymo
What have you tried so far?

@tommymo
I suppose both events are raised...I've just never heard of or actually used the OnTextChanged event.
Feb 25 '09 #6

P: 5
ive tried working through your example however i dont understand VB. Further More I feel that its hard to understand what your doing with your code. I understand you want to make points and that is why you break your code into pieces, however to seems in your example that your page_init changes or is missing the previous lines of code in your examples. I think it would be clearer if you submitted your entire code set versus jumping around.
Feb 25 '09 #7

Frinavale
Expert Mod 5K+
P: 9,731
Right. I guess I have to actually add C# code to my example....

I'll do my best to explain using C# syntax....but please remember that I'm not strong with this language so I may get something wrong.

So, in your page you need to declare 2 "somethings" that will contain the RadioListButtons and the Labels. I recommended earlier that you should consider using Lists to contain the controls. Now, since these controls need to be accessed throughout the page code you need to declare this at page level:
Expand|Select|Wrap|Line Numbers
  1.   List<RadioButtonList> possibleAnswers;
  2.   List<Label> questionPrompts;
  3.  
  4. protected void Page_Load(object sender, EventArgs e)
  5.     {
  6.  
  7.     }
  8.  
  9. //.....
Now, like I mentioned in the article, you need to create instances of the controls in your Page Init event.
Expand|Select|Wrap|Line Numbers
  1.   List<RadioButtonList> possibleAnswers;
  2.   List<Label> questionPrompts;
  3.  
  4.  
  5. protected void Page_Init(object sender, EventArgs e)
  6. {
  7.    possibleAnswers= New List<RadioButtonList>;
  8.    questionPrompts = New List<Labels>;
  9.  
  10. //Now you need to connect to your database and populate the lists just instantiated with the questions and possible answers..
  11.  
  12. //Once you're finished creating these, add each one of them to your page, panel, or whatever you're adding them to
  13. }
  14.  
  15. protected void Page_Load(object sender, EventArgs e)
  16. {
  17.  
  18. }
  19.  
  20.  
  21. //.....
Now because the Page Init event happens before the viewstate is loaded, your dynamically created Labels and RadioButton's will be loaded with what was submitted to the page.

Later you can access these controls without a problem....

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. protected void  Button1_Click(object sender, EventArgs e)
  4. {
  5.    //for each RadioButtonList in the 
  6.   //(possibleAnswers) list of RadioButtonLists
  7.   //retrieve the user's selection
  8.  
  9. }
Feb 25 '09 #8

P: 5
OK it is making more sence. What I dont understand is how am I going to load the questions in the page_init when i dont know what the user has picked in the drop down list?
Feb 25 '09 #9

Frinavale
Expert Mod 5K+
P: 9,731
That is loaded after the Page Init is done....for you....
You just have to make sure that the object exist for this to happen.
Feb 25 '09 #10

P: 32
try this code of vb

You can easily convert to c#
Expand|Select|Wrap|Line Numbers
  1.  
  2.  Dim rd As New RadioButtonList
  3.         rd.ID = "rd"
  4.         rd.SelectedValue = ""
  5.         rd.CssClass = "pollRadio"
  6.         rd.TextAlign = TextAlign.Left
  7.  
  8.         rd.EnableViewState = False
  9.         query = "select * from tbl_subpollquestioninfo  where pollquestionid='" & val & "'"
  10.         ds = obj.GetDataSet(query)
  11.  
  12.         If ds.Tables(0).Rows.Count > 0 Then
  13.  
  14.  
  15.             For i = 0 To ds.Tables(0).Rows.Count - 1
  16.                 hidden_id.Value = ds.Tables(0).Rows.Count
  17.  
  18.                 'Start of New Table'
  19.  
  20.                 If Trim(ds.Tables(0).Rows(0)("type").ToString) = "text" Then
  21.                     Dim item As New ListItem
  22.                     item.Text = ds.Tables(0).Rows(i)("option1")
  23.                     item.Value = ds.Tables(0).Rows(i)("id")
  24.                     rd.Items.Add(item)
  25.  
  26.                 Else
  27.                     Dim item As New ListItem
  28.                     item.Text = "<img src=../PollQuestionImage/" & ds.Tables(0).Rows(i)("option1") & " >"
  29.                     item.Value = ds.Tables(0).Rows(i)("id")
  30.                     rd.Items.Add(item)
  31.  
  32.                 End If
  33.  
  34.  
  35.  
  36.             Next
  37.             plcBanner.Controls.Add(rd)
Feb 27 '09 #11

P: 32
@tommymo
Hi Tommymo

Use this code

//Code of Html
Expand|Select|Wrap|Line Numbers
  1.  <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
  2.             DataTextField="Role_Name" DataValueField="Role_ID" OnTextChanged="get_question">
  3.             <asp:ListItem Text="1" Value="1"></asp:ListItem>
  4.                         <asp:ListItem Text="2" Value="2"></asp:ListItem>
  5.                         <asp:ListItem Text="3" Value="3"></asp:ListItem>
  6.             <asp:ListItem Text="4" Value="4"></asp:ListItem>
  7.             </asp:DropDownList>
  8.         </asp:DropDownList><asp:SqlDataSource ID="QaQuestions" runat="server" ConnectionString="<%$ ConnectionStrings:QAquestionConnectionString %>" 
  9.             SelectCommand="SELECT [Role_Name], [Role_ID] FROM [Role]"></asp:SqlDataSource> 
  10.  
  11.        <asp:Panel ID="Panel1" runat="server" Height="50px" Width="500px"> 
  12.         </asp:Panel>
  13.  
  14.  
  15.         <asp:button ID="Button1" runat="server" text="Submit" OnClick="Button1_Click" /> 

//Code of C#

Expand|Select|Wrap|Line Numbers
  1.   protected void Page_Load(object sender, EventArgs e)
  2.     {
  3.       if(Page.IsPostBack==false)
  4.       {}
  5.     }
  6.     void fillcontrols()
  7.     {
  8.         Label question = new Label();
  9.         question.ID = "lbl";
  10.         question.Text = "how do you like your job?";
  11.         Panel1.Controls.Add(question);
  12.         TextBox txt = new TextBox();
  13.         txt.ID = "txt";
  14.         txt.Text = "hi";
  15.         Panel1.Controls.Add(txt);
  16.         RadioButtonList radio = new RadioButtonList();
  17.         radio.ID = "radio_1";
  18.         radio.RepeatDirection = RepeatDirection.Horizontal;
  19.         radio.Items.Add(new ListItem("Yes", "1"));
  20.         radio.Items.Add(new ListItem("No", "2"));
  21.         radio.Items.Add(new ListItem("N/A", "3"));
  22.  
  23.         Panel1.Controls.Add(radio);
  24.  
  25.     }
  26.      protected void get_question(object sender, EventArgs e) 
  27.     {
  28.         fillcontrols();
  29.  
  30.     }
  31.  
  32.  
  33.     protected void Button1_Click(object sender, EventArgs e)
  34.     {
  35.         fillcontrols();
  36.         // Find control on page. 
  37.         //RadioButtonList radio1 = (RadioButtonList)Panel1.FindControl("radio_1");
  38.  
  39.  
  40.  
  41.        Control myControl1 = FindControl("radio_1");
  42.  
  43.        if (myControl1 != null)
  44.        {
  45.            // Get control's parent. 
  46.            Control myControl2 = myControl1.Parent;
  47.  
  48.            Response.Write("Parent of the text box is : " + myControl2.ID);
  49.        }
  50.        else
  51.        {
  52.            Response.Write("Control not found");
  53.        } 
  54.     }
Feb 27 '09 #12

Frinavale
Expert Mod 5K+
P: 9,731
Hi Bhupinder,

Tommymo needs to dynamically create the asp.net controls because he doesn't know how many he needs until run time. Your solution will work fine if this wasn't his requirement.


PS. Could you please start using [code] tags whenever you post code.

-Frinny
Feb 27 '09 #13

Frinavale
Expert Mod 5K+
P: 9,731
@tommymo
Wait a sec, does the number of questions depend on a DropDownList?

In this case you need to store this somewhere that is accessible in the Page Init event....you can use a cookie or a hidden field for this because Session and ViewState are not available in the Page Init.

For example, in the DropDownList SelectedIndexChanged event you would dynamically create your questions and then store this number in a hidden field named "hidden_numberOfQuestions" (which you'll have to add to the page).

Now in your Page Init event, you retrieve the number of questions that exist on the page from the hidden field:
Expand|Select|Wrap|Line Numbers
  1. int _numQuestions;
  2. protected void Page_Init(object sender, EventArgs e)
  3. {
  4.         'Retrieving the number of questions that were created on the page:
  5.         Integer.TryParse(Request.Params("hidden_numberOfQuestions"),_numQuestions);
  6.  
  7. //now populate the lists and add the dynamically create controls to the  page
  8.  
  9. }
Feb 27 '09 #14

Post your reply

Sign in to post your reply or Sign up for a free account.