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.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="QaQuestions"
DataTextField="Role_Name" DataValueField="Role_ID" OnTextChanged="get_question">
</asp:DropDownList><asp:SqlDataSource ID="QaQuestions" runat="server" ConnectionString="<%$ ConnectionStrings:QAquestionConnectionString %>"
SelectCommand="SELECT [Role_Name], [Role_ID] FROM [Role]"></asp:SqlDataSource>
<asp:Panel ID="Panel1" runat="server" Height="50px" Width="500px">
</asp:Panel>
<asp:button ID="Button1" runat="server" text="Submit" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
The c# code
protected void Page_Load(object sender, EventArgs e)
{
}
protected void get_question(object sender, EventArgs e)
{
Label question = new Label();
question.Text = "how do you like your job?";
Panel1.Controls.Add(question);
RadioButtonList radio = new RadioButtonList();
radio.ID = "radio_1";
radio.RepeatDirection = RepeatDirection.Horizontal;
radio.Items.Add(new ListItem("Yes","1"));
radio.Items.Add(new ListItem("No","2"));
radio.Items.Add(new ListItem("N/A","3"));
Panel1.Controls.Add(radio);
}
protected void Button1_Click(object sender, EventArgs e)
{
// Find control on page.
Control myControl1 = FindControl("radio_1");
if (myControl1 != null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
}
else
{
Response.Write("Control not found");
}