|
 |
aspx thread: How can I access dynamically added controls fields from SubmitButton_Click sub?
Message #1 by ofer kar <oferkarp@y...> on Thu, 6 Jun 2002 00:19:41 -0700 (PDT)
|
|
Need your help urgently!
I'm writing a web survey client side page. This page
consists of different controls (checkboxlists,
dropdownlists, textboxs, etc.) which are created
according to a SQL database.
Therefore, I have to add the controls programmatically
and dynamically (I do this using a panel control).
This works fine, however, when the user clicks the
submit button - I can't access any of those controls,
in fact it looks like the panel is empty!
I add the controls to the panel in Page_Load sub,
checking that it's the first time the page is loaded
by "If Not IsPostBack", and if I remove this check - I
get an error for using the same ID for multiple
contorls.
What can I do? I'd appreciate any answer!
Here's my code:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents SqlConnection1 As
System.Data.SqlClient.SqlConnection
Protected WithEvents cmdGetSurveyConf As
System.Data.SqlClient.SqlCommand
Protected WithEvents cmdGetQuestions As
System.Data.SqlClient.SqlCommand
Protected WithEvents Panel1 As
System.Web.UI.WebControls.Panel
Protected WithEvents SubmitButton As
System.Web.UI.WebControls.Button
Protected WithEvents Label1 As
System.Web.UI.WebControls.Label
Protected WithEvents FindClientAnswers As
System.Data.SqlClient.SqlCommand
'Private WithEvents ClientName As
System.Web.UI.WebControls.TextBox = New TextBox()
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private
Sub InitializeComponent()
Me.SqlConnection1 = New
System.Data.SqlClient.SqlConnection()
Me.cmdGetSurveyConf = New
System.Data.SqlClient.SqlCommand()
Me.cmdGetQuestions = New
System.Data.SqlClient.SqlCommand()
Me.FindClientAnswers = New
System.Data.SqlClient.SqlCommand()
'
'SqlConnection1
'
Me.SqlConnection1.ConnectionString = "initial
catalog=O2_2_5;integrated security=SSPI;persist
security info=False;works" & _
"tation id=OFER;packet size=4096"
'
'cmdGetSurveyConf
'
Me.cmdGetSurveyConf.CommandText = "SELECT
SURVEYS.* FROM SURVEYS WHERE (ID = @surveyid)"
Me.cmdGetSurveyConf.Connection
Me.SqlConnection1
Me.cmdGetSurveyConf.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@surveyid",
System.Data.SqlDbType.Decimal, 9,
System.Data.ParameterDirection.Input, False, CType(18,
Byte), CType(0, Byte), "ID",
System.Data.DataRowVersion.Current, Nothing))
'
'cmdGetQuestions
'
Me.cmdGetQuestions.CommandText = "SELECT
QUESTIONS.* FROM QUESTIONS WHERE (SURVEY_ID
@surveyid)"
Me.cmdGetQuestions.Connection
Me.SqlConnection1
Me.cmdGetQuestions.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@surveyid",
System.Data.SqlDbType.Decimal, 9,
System.Data.ParameterDirection.Input, False, CType(18,
Byte), CType(0, Byte), "SURVEY_ID",
System.Data.DataRowVersion.Current, Nothing))
'
'FindClientAnswers
'
Me.FindClientAnswers.CommandText = "SELECT
ANSWERS.* FROM ANSWERS WHERE (USERNAME = @username)"
Me.FindClientAnswers.Connection
Me.SqlConnection1
Me.FindClientAnswers.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@username",
System.Data.SqlDbType.NVarChar, 50, "USERNAME"))
End Sub
Private Sub Page_Init(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Init
'CODEGEN: This method call is required by the
Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Dim UserName As String
Dim Anonymous As Boolean = True
Private Sub Page_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
If Not IsPostBack Then
Dim surveyid As String
Dim QuestionType As Int16
Dim Answers As String
Dim firstrow As Boolean = True
Dim Trusted As Boolean = True
Dim Layout As Int16
Dim QuestionNumber As Int16 = 0
Dim ValidConf As Boolean = True
Dim Surveydreader As
SqlClient.SqlDataReader
Dim Questiondreader As
SqlClient.SqlDataReader
Dim Check As String
surveyid = Request.QueryString("SurveyId")
'surveyid = "2"
surveyid = "1"
cmdGetSurveyConf.Parameters("@surveyid").Value
surveyid
cmdGetQuestions.Parameters("@surveyid").Value
surveyid
SqlConnection1.Open()
Surveydreader
cmdGetSurveyConf.ExecuteReader()
Surveydreader.Read()
'Dim Label1 As Label = New Label()
Label1.Text = "Welcome to survey" &
Surveydreader(1).ToString()
Label1.Text += "<br>"
Label1.Text += "Please answer the
following questions:"
Trusted = Surveydreader(4)
Anonymous = Surveydreader(3)
Surveydreader.Close()
If (Anonymous = -1) Then
Dim ClientName As TextBox = New
TextBox()
Dim ClientNameLabel As Label = New
Label()
ClientNameLabel.Text() = "Please Enter
your name:"
Panel1.Controls.Add(ClientNameLabel)
Panel1.Controls.Add(ClientName)
Dim spacer As LiteralControl = New
LiteralControl("<br>")
Panel1.Controls.Add(spacer)
End If
Questiondreader
cmdGetQuestions.ExecuteReader()
While Questiondreader.Read()
QuestionNumber += 1
Dim QuestionLable As Label = New
Label()
QuestionLable.Text
QuestionNumber.ToString
QuestionLable.Text += ") "
QuestionLable.Text +
Questiondreader(3).ToString
QuestionLable.ID = "Label" &
QuestionNumber
Panel1.Controls.Add(QuestionLable)
Dim spacer As LiteralControl = New
LiteralControl("<br>")
Panel1.Controls.Add(spacer)
QuestionType = Questiondreader(2)
Select Case QuestionType
Case 1
Dim MyDDL As DropDownList
New DropDownList()
Answers = Questiondreader(4)
Dim AnswersArray As Array
ReturnAnswers(Answers)
Dim i As Integer
For i = 0 To
AnswersArray.Length - 1
MyDDL.Items.Add(AnswersArray(i))
Next
Panel1.Controls.Add(MyDDL)
Panel1.Controls.Add(spacer)
Case 2
Dim MyCBL As CheckBoxList
New CheckBoxList()
Answers = Questiondreader(4)
Dim AnswersArray As Array
ReturnAnswers(Answers)
Dim i As Integer
For i = 0 To
AnswersArray.Length - 1
MyCBL.Items.Add(AnswersArray(i))
Next
Panel1.Controls.Add(MyCBL)
Panel1.Controls.Add(spacer)
Case 3
Dim MyDDL As DropDownList
New DropDownList()
MyDDL.Items.Add("Yes")
MyDDL.Items.Add("No")
Panel1.Controls.Add(MyDDL)
Panel1.Controls.Add(spacer)
Case 4
Dim MyTextBox As TextBox = New
TextBox()
Panel1.Controls.Add(MyTextBox)
Panel1.Controls.Add(spacer)
Case 5
Dim MyTextBox As TextBox = New
TextBox()
Dim NumValidator As
RegularExpressionValidator = New
RegularExpressionValidator()
'NumValidator.ControlToValidate = "MyTextBox"
'NumValidator.ValidationExpression = "\d(5)"
'NumValidator.ErrorMessage
"You should enter a number"
Panel1.Controls.Add(MyTextBox)
'Panel1.Controls.Add(NumValidator)
Panel1.Controls.Add(spacer)
End Select
End While
SqlConnection1.Close()
End If
End Sub
Private Function ReturnAnswers(ByVal Answers As
String) As Array
Return Split(Answers, ";;;")
End Function
Private Sub SubmitButton_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
SubmitButton.Click
SqlConnection1.Open()
If (Anonymous = -1) Then
Dim Userdreader As SqlClient.SqlDataReader
Dim Num As String = Panel1.Controls.Count
If Panel1.HasControls() Then
Response.Output.Write("has controls")
End If
FindClientAnswers.Parameters("@username").Value
Panel1.FindControl("ClientName")
Userdreader
FindClientAnswers.ExecuteReader()
If Userdreader.Read() Then
Server.Transfer("http://localhost/ClientApp/SurveyClientAccessDenied.aspx")
End If
End If
SqlConnection1.Close()
End Sub
End Class
__________________________________________________
Do You Yahoo!?
Yahoo! - Official partner of 2002 FIFA World Cup
http://fifaworldcup.yahoo.com
Message #2 by Feduke Cntr Charles R <FedukeCR@m...> on Thu, 6 Jun 2002 09:38:21 -0400
|
|
I had (and still have) this problem. You must add your controls
before the Page_OnInit event is completed for them to get wired up properly.
You could potentially declare private instances of controls which solves
this problem (and then set those controls to real controls later on during
processing). Then you need to do something like...
Page.RegisterRequiresPostBack(control);
in your Page_OnLoad event. There are several other Page.Register* methods
that also might be able to help.
Panel.EnsureChildControls();
wouldn't hurt either (if you're doing any type of data binding). Finally,
if you need to wire up to an event (such as SelectionChanged or Click) you'd
need to do some magic like this:
Page.RegisterRequiresPostBack(control);
this.AddedControl(control, 0);
The MSDN documentation says not to use the AddedControl method
directly in your code, but I have found no other way to link controls to
their appropriate events dynamically.
HTH,
- Chuck
-----Original Message-----
From: ofer kar [mailto:oferkarp@y...]
Sent: Thursday, June 06, 2002 3:20 AM
To: ASP+
Subject: [aspx] How can I access dynamically added controls fields from
SubmitButton_Click sub?
Need your help urgently!
I'm writing a web survey client side page. This page
consists of different controls (checkboxlists,
dropdownlists, textboxs, etc.) which are created
according to a SQL database.
Therefore, I have to add the controls programmatically
and dynamically (I do this using a panel control).
This works fine, however, when the user clicks the
submit button - I can't access any of those controls,
in fact it looks like the panel is empty!
I add the controls to the panel in Page_Load sub,
checking that it's the first time the page is loaded
by "If Not IsPostBack", and if I remove this check - I
get an error for using the same ID for multiple
contorls.
What can I do? I'd appreciate any answer!
Here's my code:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents SqlConnection1 As
System.Data.SqlClient.SqlConnection
Protected WithEvents cmdGetSurveyConf As
System.Data.SqlClient.SqlCommand
Protected WithEvents cmdGetQuestions As
System.Data.SqlClient.SqlCommand
Protected WithEvents Panel1 As
System.Web.UI.WebControls.Panel
Protected WithEvents SubmitButton As
System.Web.UI.WebControls.Button
Protected WithEvents Label1 As
System.Web.UI.WebControls.Label
Protected WithEvents FindClientAnswers As
System.Data.SqlClient.SqlCommand
'Private WithEvents ClientName As
System.Web.UI.WebControls.TextBox = New TextBox()
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private
Sub InitializeComponent()
Me.SqlConnection1 = New
System.Data.SqlClient.SqlConnection()
Me.cmdGetSurveyConf = New
System.Data.SqlClient.SqlCommand()
Me.cmdGetQuestions = New
System.Data.SqlClient.SqlCommand()
Me.FindClientAnswers = New
System.Data.SqlClient.SqlCommand()
'
'SqlConnection1
'
Me.SqlConnection1.ConnectionString = "initial
catalog=O2_2_5;integrated security=SSPI;persist
security info=False;works" & _
"tation id=OFER;packet size=4096"
'
'cmdGetSurveyConf
'
Me.cmdGetSurveyConf.CommandText = "SELECT
SURVEYS.* FROM SURVEYS WHERE (ID = @surveyid)"
Me.cmdGetSurveyConf.Connection
Me.SqlConnection1
Me.cmdGetSurveyConf.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@surveyid",
System.Data.SqlDbType.Decimal, 9,
System.Data.ParameterDirection.Input, False, CType(18,
Byte), CType(0, Byte), "ID",
System.Data.DataRowVersion.Current, Nothing))
'
'cmdGetQuestions
'
Me.cmdGetQuestions.CommandText = "SELECT
QUESTIONS.* FROM QUESTIONS WHERE (SURVEY_ID
@surveyid)"
Me.cmdGetQuestions.Connection
Me.SqlConnection1
Me.cmdGetQuestions.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@surveyid",
System.Data.SqlDbType.Decimal, 9,
System.Data.ParameterDirection.Input, False, CType(18,
Byte), CType(0, Byte), "SURVEY_ID",
System.Data.DataRowVersion.Current, Nothing))
'
'FindClientAnswers
'
Me.FindClientAnswers.CommandText = "SELECT
ANSWERS.* FROM ANSWERS WHERE (USERNAME = @username)"
Me.FindClientAnswers.Connection
Me.SqlConnection1
Me.FindClientAnswers.Parameters.Add(New
System.Data.SqlClient.SqlParameter("@username",
System.Data.SqlDbType.NVarChar, 50, "USERNAME"))
End Sub
Private Sub Page_Init(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Init
'CODEGEN: This method call is required by the
Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
Dim UserName As String
Dim Anonymous As Boolean = True
Private Sub Page_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
If Not IsPostBack Then
Dim surveyid As String
Dim QuestionType As Int16
Dim Answers As String
Dim firstrow As Boolean = True
Dim Trusted As Boolean = True
Dim Layout As Int16
Dim QuestionNumber As Int16 = 0
Dim ValidConf As Boolean = True
Dim Surveydreader As
SqlClient.SqlDataReader
Dim Questiondreader As
SqlClient.SqlDataReader
Dim Check As String
surveyid = Request.QueryString("SurveyId")
'surveyid = "2"
surveyid = "1"
cmdGetSurveyConf.Parameters("@surveyid").Value
surveyid
cmdGetQuestions.Parameters("@surveyid").Value
surveyid
SqlConnection1.Open()
Surveydreader
cmdGetSurveyConf.ExecuteReader()
Surveydreader.Read()
'Dim Label1 As Label = New Label()
Label1.Text = "Welcome to survey" &
Surveydreader(1).ToString()
Label1.Text += "<br>"
Label1.Text += "Please answer the
following questions:"
Trusted = Surveydreader(4)
Anonymous = Surveydreader(3)
Surveydreader.Close()
If (Anonymous = -1) Then
Dim ClientName As TextBox = New
TextBox()
Dim ClientNameLabel As Label = New
Label()
ClientNameLabel.Text() = "Please Enter
your name:"
Panel1.Controls.Add(ClientNameLabel)
Panel1.Controls.Add(ClientName)
Dim spacer As LiteralControl = New
LiteralControl("<br>")
Panel1.Controls.Add(spacer)
End If
Questiondreader
cmdGetQuestions.ExecuteReader()
While Questiondreader.Read()
QuestionNumber += 1
Dim QuestionLable As Label = New
Label()
QuestionLable.Text
QuestionNumber.ToString
QuestionLable.Text += ") "
QuestionLable.Text +
Questiondreader(3).ToString
QuestionLable.ID = "Label" &
QuestionNumber
Panel1.Controls.Add(QuestionLable)
Dim spacer As LiteralControl = New
LiteralControl("<br>")
Panel1.Controls.Add(spacer)
QuestionType = Questiondreader(2)
Select Case QuestionType
Case 1
Dim MyDDL As DropDownList
New DropDownList()
Answers = Questiondreader(4)
Dim AnswersArray As Array
ReturnAnswers(Answers)
Dim i As Integer
For i = 0 To
AnswersArray.Length - 1
MyDDL.Items.Add(AnswersArray(i))
Next
Panel1.Controls.Add(MyDDL)
Panel1.Controls.Add(spacer)
Case 2
Dim MyCBL As CheckBoxList
New CheckBoxList()
Answers = Questiondreader(4)
Dim AnswersArray As Array
ReturnAnswers(Answers)
Dim i As Integer
For i = 0 To
AnswersArray.Length - 1
MyCBL.Items.Add(AnswersArray(i))
Next
Panel1.Controls.Add(MyCBL)
Panel1.Controls.Add(spacer)
Case 3
Dim MyDDL As DropDownList
New DropDownList()
MyDDL.Items.Add("Yes")
MyDDL.Items.Add("No")
Panel1.Controls.Add(MyDDL)
Panel1.Controls.Add(spacer)
Case 4
Dim MyTextBox As TextBox = New
TextBox()
Panel1.Controls.Add(MyTextBox)
Panel1.Controls.Add(spacer)
Case 5
Dim MyTextBox As TextBox = New
TextBox()
Dim NumValidator As
RegularExpressionValidator = New
RegularExpressionValidator()
'NumValidator.ControlToValidate = "MyTextBox"
'NumValidator.ValidationExpression = "\d(5)"
'NumValidator.ErrorMessage
"You should enter a number"
Panel1.Controls.Add(MyTextBox)
'Panel1.Controls.Add(NumValidator)
Panel1.Controls.Add(spacer)
End Select
End While
SqlConnection1.Close()
End If
End Sub
Private Function ReturnAnswers(ByVal Answers As
String) As Array
Return Split(Answers, ";;;")
End Function
Private Sub SubmitButton_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
SubmitButton.Click
SqlConnection1.Open()
If (Anonymous = -1) Then
Dim Userdreader As SqlClient.SqlDataReader
Dim Num As String = Panel1.Controls.Count
If Panel1.HasControls() Then
Response.Output.Write("has controls")
End If
FindClientAnswers.Parameters("@username").Value
Panel1.FindControl("ClientName")
Userdreader
FindClientAnswers.ExecuteReader()
If Userdreader.Read() Then
Server.Transfer("http://localhost/ClientApp/SurveyClientAccessDenied.aspx")
End If
End If
SqlConnection1.Close()
End Sub
End Class
__________________________________________________
Do You Yahoo!?
Yahoo! - Official partner of 2002 FIFA World Cup
http://fifaworldcup.yahoo.com
Message #3 by "Ofer Karp" <oferkarp@y...> on Thu, 6 Jun 2002 18:52:24
|
|
Thanks alot Chuck,
However I must admit I'm a bit confused by your answer. I never read
about those methods that you mentioned.
Where do you mean that I should declare the controls as private? In the
Page_Load sub or in Page_OnInit? I can't make them global, because I have
to check the SQL before I know which controls I need.
I'd appreciate it a lot if you could write a short code which adds one
control dynamically (lets say a textbox), and then, when submitted, gets
it's value.
Thanks again, Ofer.
> I had (and still have) this problem. You must add your controls
before the Page_OnInit event is completed for them to get wired up
properly.
You could potentially declare private instances of controls which solves
this problem (and then set those controls to real controls later on during
processing). Then you need to do something like...
Page.RegisterRequiresPostBack(control);
in your Page_OnLoad event. There are several other Page.Register* methods
that also might be able to help.
Panel.EnsureChildControls();
wouldn't hurt either (if you're doing any type of data binding). Finally,
if you need to wire up to an event (such as SelectionChanged or Click)
you'd
need to do some magic like this:
Page.RegisterRequiresPostBack(control);
this.AddedControl(control, 0);
The MSDN documentation says not to use the AddedControl method
directly in your code, but I have found no other way to link controls to
their appropriate events dynamically.
HTH,
- Chuck
Message #4 by Feduke Cntr Charles R <FedukeCR@m...> on Thu, 6 Jun 2002 13:56:06 -0400
|
|
Ofer,
> Page_Load sub or in Page_OnInit? I can't make them global, because I have
> to check the SQL before I know which controls I need.
Precisely. :) They must be global private to the class so ASP.NET
can properly wire up the controls as necessary. You will have to make an
array of controls (or make something from NameObjectCollectionBase for
Control) for this to *maybe* work. I say *maybe* because although this
method works on my machine as the server, it does not work on my co-worker's
machine when he's running as the server (he may be implementing it wrong
though). Problems arise when you try to link controls to event delegates
(for example, a OnClick or OnSelectedIndexChanged).
Here's my example in a DropDownList I have extended to include a
AddCommand event.
private LinkButton add = new LinkButton();
protected override void OnInit(System.EventArgs e)
{
// create our link button for add new command
base.OnInit(e);
add.EnableViewState = true;
add.Text = _addNewCaption;
add.Command += AddCommand;
Page.RegisterRequiresRaiseEvent(add);
this.AddedControl(add, 0);
}
Then in my Render event I make add.Visible = _allowAdd (_allowAdd is
a bool that determines if the add link is shown).
HTH,
- Chuck
-----Original Message-----
From: Ofer Karp [mailto:oferkarp@y...]
Sent: Thursday, June 06, 2002 2:52 PM
To: ASP+
Subject: [aspx] RE: How can I access dynamically added controls fields
fro m SubmitButton_Click sub?
Thanks alot Chuck,
However I must admit I'm a bit confused by your answer. I never read
about those methods that you mentioned.
Where do you mean that I should declare the controls as private? In the
Page_Load sub or in Page_OnInit? I can't make them global, because I have
to check the SQL before I know which controls I need.
I'd appreciate it a lot if you could write a short code which adds one
control dynamically (lets say a textbox), and then, when submitted, gets
it's value.
Thanks again, Ofer.
> I had (and still have) this problem. You must add your controls
before the Page_OnInit event is completed for them to get wired up
properly.
You could potentially declare private instances of controls which solves
this problem (and then set those controls to real controls later on during
processing). Then you need to do something like...
Page.RegisterRequiresPostBack(control);
in your Page_OnLoad event. There are several other Page.Register* methods
that also might be able to help.
Panel.EnsureChildControls();
wouldn't hurt either (if you're doing any type of data binding). Finally,
if you need to wire up to an event (such as SelectionChanged or Click)
you'd
need to do some magic like this:
Page.RegisterRequiresPostBack(control);
this.AddedControl(control, 0);
The MSDN documentation says not to use the AddedControl method
directly in your code, but I have found no other way to link controls to
their appropriate events dynamically.
HTH,
- Chuck
Message #5 by "Ofer Karp" <oferkarp@y...> on Thu, 6 Jun 2002 19:12:52
|
|
Thanks Chuck,
I'll try it and lets see if my machine likes me :)
Ofer.
|
|
 |