Showing posts with label dynamically. Show all posts
Showing posts with label dynamically. Show all posts

Monday, March 26, 2012

populate data from dynamically loaded controls.

im doing a survey system for my project but encountered a verychallenging problem. i hope gurus could help me out. i am in despratesituation.
ASP.NET 1.1 code:
Page_load():
Dim dr2As System.Data.IDataReader = getQuestion(Request.QueryString("qid"))
Dim qnumAsInteger = 1
While (dr2.Read())
Dim l1AsNew Literal
l1.Text += vbNewLine & "Q" & qnum.ToString() & ") " & dr2.Item("qtxt") & ""
l1.Text += vbNewLine & "<input type='hidden' value='" & dr2.Item("qid") & "' name='qid'>"

ph1.Controls.Add(l1)
If dr2.Item("qtype").ToString() = "RadioButton"Then
Dim radiogrpAsNew RadioButtonList
radiogrp.DataSource = getAnswer(dr2.Item("qid"))
radiogrp.ID = "aid".ToString & dr2.Item("qid")
radiogrp.DataTextField = "atxt"
radiogrp.DataValueField = "aid"
radiogrp.DataBind()
ph1.Controls.Add(radiogrp)
EndIf
qnum += 1
End While

the code above is my code to display the survey quesitons (qid) and theanswers (selection,choices,aid) for the particular question.
a sample of .aspx that the code above generated could be found here :http://www.valenhsu.com/WebForm1.aspx.htm
look at the html source, lok at the IDs..
the problem is i do not know how to populate the use input. unlikestatic pre-created controls, the id is different and the quantity ofeach control is unknown.
ASP.NET 1.1 code:
button1_click:
'populate user input and stores into a database.
'how ?



please help. please.Look at the Repeater control, it was designed for things just like this.
repeater would not be suitable as i may have checkboxes also.


Hi,

I agree with Curt_C, your task can surely be accomplished using a Repeater, even if you have Checkboxes or other web controls, because you can decide exactly how each item is rendered, and you can decide if a particular control (inside a Repeater item) will be rendered or not in that particular item (recall that each WebControl has a Visible property that determines if the control will be rendered on Page or not).

All you have to do is build an ItemTemplate for your Repeater, with all the web controls that may be needed, and then declare an event handler for the ItemDataBound event. This event is raised when a RepeaterItem is associated with a particular object in the Repeater's data source.

For example, let's build an ItemTemplate for a generic question,

<asp:Repeater id="repQuestions" runat="server">
<ItemTemplate>
<div>
<asp:RadioButtonList id="rbAnswers" runat="server"></asp:RadioButtonList>
<asp:CheckBoxList id="cbAnswers" runat="server"></asp:CheckBoxList>
<asp:TextBox id="txtAnswer" runat="server"></asp:CheckBox>
</div>
</ItemTemplate>
</asp:Repeater>

The ItemTemplate holds a RadioButtonList, a CheckBoxList and a TextBox. You can add all the controls that a question may need.

Now, suppose that a queston deals only with the RadioButtonList. Well, you will bind the RadioButtonList, leave the CheckBoxList unbound and set the Visible property of the TextBox to false.
Again, suppose that a question needs only the TextBox. Then, leave the RadioButtonList and the CheckBoxList unbound.

void repQuestions_ItemDataBound(object sender, RepeaterItemEventArgs e){

switch(e.Item.ItemType) {
case ListItemType.Item:
case LIstItemType.AlternatingItem:



// Get a reference to the web controls for this item.
RadioButtonList rbAnswers = (RadioButtonList)e.Item.FindControl("rbAnswers");
CheckBoxList cbAnswers = (CheckBoxList)e.Item.FindControl("cbAnswers");
TextBox txtAnswer = (TextBox)e.Item.FindControl("txtAnswer");

// Based on the type of questions, set the layout for this item.
// For example,
// bind the RadioButtonList
rbAnswers.DataSource = // Get the data source
rbAnswers.DataBind();

// Leave the CheckBoxList unbound (no-op).

// This question doesn't need a TextBox.
txtAnswer.Visible = false;
break;

default:break;
}
}

The only thing you have to care is the binding strategy, ie how to bind the questions to the Repeater. It is not a difficult task (I think it's a lot easier than dealing with many dynamic controls), for example you can bind the question Repeater to an array of question IDs and then, for each item, get the question ID and do a database query to retrieve all the info for that question. Or you can build a Question class that encapsulates all the information needed, then access the database to populate a collection of Question objects and bind this collection
to the Repeater (this would be my preferred approach), and so on.

The Repeater approach may seem a lot more complicated that the dynamic controls approach... maybe it requires more coding, but avoids a ton of problems that you have to face when dealing with dynamic controls handling, makes the code more readable and organizable, makes easy to persist the control hierarchy during postbacks and it is a general approach for this kind of problem.

The use of a general ItemTemplate that encapsulates all the possible controls needed for a question and renders only a couple of them may seem a "waste of instances" and have impact on performance. Well, I think that unless your questionary is made up of 100s questions, impact on performance is trascurable (I can even chache the Page output depending on the querystring "qid" value) while impact on code readability and maintainability is notable.

Sure, there are alternative approaches. For example, if I need those dynamic controls only for the first Request and then, when the page is posted back, I need only to collect the user input and save it to database, I could build a "map" of the dynamic controls involved for each question, where "1,rbaid1,cbaid1,tbaid1" is a string containing the question id and all the control IDs (ClientID) associated with that question.
I can build this string while I am reading records from the DataReader and building dynamic controls, then store this string in a string[] array and persist it to ViewState. On postback, I will parse the string, get all the IDs and the types of control (the first two letters of each control ID, easy) and use Request.Form[controlID] to get the user input, or maybe recreate instances for them
if I saved the server ID. This seems an easier approach but I do not recommend using
it because it is unaware of ASP.NET features,
is not a generalizable approach and you will need to think "from scratch" every
time you face this kind of task.


Hi,

the following is a complete working example (it is written in C#, but you can use one of the many converters available) that shows how to build and manage a dynamic questionary using a Repeater.

Please note that it is only an example and it lacks error checking and optimization. I hope it gives you some ideas on how to solve your problem.

<%@.PageLanguage="C#" %>

<%@.ImportNamespace="System.Data" %>

<scriptrunat="server">

protectedDataTable questions;

protectedDataTable answers;

protectedbool isAnswered =false;

privatevoid Page_Load(object sender,EventArgs e)

{

// Build the data structure and insert data used

// in this example.

BuildTables();

PopulateTables();

if (!Page.IsPostBack)

{

// Bind the question Repeater with a list

// of question IDs.

ArrayList quids =newArrayList();

foreach (DataRow rowin questions.Rows)

{

quids.Add(row["ID"]);

}

repQuestions.DataSource = quids;

repQuestions.DataBind();

}

}

// This method handles the ItemDataBound event of the question Repeater.

// It calls HandleQuestionItem passing a repeater item as an argument.

privatevoid repQuestions_ItemDataBound(object sender,RepeaterItemEventArgs e)

{

switch (e.Item.ItemType)

{

caseListItemType.Item:

caseListItemType.AlternatingItem:

HandleQuestionItem(e.Item);

break;

default:break;

}

}

// This method handles a question represented by a Repeater item.

// The flag isAnswered is used to determine if the questionary

// has been answered.

privatevoid HandleQuestionItem(RepeaterItem item)

{

// Get references to the controls contained in this item.

HtmlInputHidden questionID = (HtmlInputHidden)item.FindControl("questionID");

Label lblText = (Label)item.FindControl("lblText");

RadioButtonList rbAnswer = (RadioButtonList)item.FindControl("rbAnswer");

CheckBoxList cbAnswer = (CheckBoxList)item.FindControl("cbAnswer");

TextBox txtAnswer = (TextBox)item.FindControl("txtAnswer");

// Retrieve the question ID, its type and its text.

int quid = (isAnswered) ?Int32.Parse(questionID.Value) : (int)item.DataItem;

string qtype = (string)(questions.Select("ID = " + quid))[0]["Type"];

string qtext = (string)(questions.Select("ID = " + quid))[0]["Text"];

// If we are generating questions, fill the questionID field and

// the label that holds the question's text.

if (!isAnswered)

{

questionID.Value =Convert.ToString(quid);

lblText.Text = qtext;

}

// Take action based on the type of question.

switch(qtype) {

case"RadioButton":

// If answered, output a string with the answer.

if (isAnswered)

{

Response.Write("Answer to question " + questionID.Value +": " + rbAnswer.SelectedValue +"<br />");

}

else

{

// This is an example of binding a ListControl without using

// the DataBind() method.

DataRow[] rbAns = answers.Select("QuestionID =" + quid);

foreach (DataRow ansin rbAns)

{

string ansText = (string)ans["Text"];

rbAnswer.Items.Add(newListItem(ansText, ansText));

}

// This question doesn't need a TextBox to be displayed.

txtAnswer.Visible =false;

}

break;

case"CheckBox":

if (isAnswered)

{

Response.Write("Answers to question " + questionID.Value +": ");

foreach (ListItem cbin cbAnswer.Items)

{

if (cb.Selected)

{

Response.Write(cb.Value +" ");

}

}

Response.Write("<br>");

}

else

{

// Same as for the RadioButton case.

DataRow[] cbAns = answers.Select("QuestionID =" + quid);

foreach (DataRow ansin cbAns)

{

string ansText = (string)ans["Text"];

cbAnswer.Items.Add(newListItem(ansText, ansText));

}

txtAnswer.Visible =false;

}

break;

case"TextBox":

// To display only the TextBox, just leave the ListControls

// unbound.

if (isAnswered)

{

Response.Write("Answer to question " + questionID.Value +": " + txtAnswer.Text +"<br>");

}

break;

default:break;

}

}

privatevoid btnSubmit_Click(object sender,EventArgs e)

{

// The questionary has been submitted and it is

// considered answered.

isAnswered =true;

// Loop through the Repeater items to get answers.

foreach (RepeaterItem itemin repQuestions.Items)

{

HandleQuestionItem(item);

}

}

// Data used in this example. //

privatevoid PopulateTables()

{

questions.Rows.Add(2,"What's your name?","TextBox");

questions.Rows.Add(5,"How old are you?","RadioButton");

questions.Rows.Add(7,"Where were you born?","RadioButton");

questions.Rows.Add(14,"Which are your favourite web controls?","CheckBox");

answers.Rows.Add(5,"5");

answers.Rows.Add(5,"10");

answers.Rows.Add(7,"USA");

answers.Rows.Add(7,"France");

answers.Rows.Add(14,"Repeater");

answers.Rows.Add(14,"GridView");

}

privatevoid BuildTables()

{

questions =newDataTable("Questions");

questions.Columns.Add(newDataColumn("ID",typeof(int)));

questions.Columns.Add(newDataColumn("Text",typeof(string)));

questions.Columns.Add(newDataColumn("Type",typeof(string)));

answers =newDataTable("Answers");

answers.Columns.Add(newDataColumn("QuestionID",typeof(int)));

answers.Columns.Add(newDataColumn("Text",typeof(string)));

}

</script>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

<styletype="text/css">

.container{width:80%;margin:auto;}

.question {width:90%;margin:auto;border:outset1px;padding:3px;margin-bottom:10px;}

.button{width:90%;margin:auto;text-align:left;}

</style>

</head>

<body>

<formid="form1"runat="server">

<divclass="container">

<asp:RepeaterID="repQuestions"Runat="server"

OnItemDataBound="repQuestions_ItemDataBound">

<ItemTemplate>

<divclass="question">

<inputtype="hidden"id="questionID"runat="server"/>

<div><asp:LabelID="lblText"runat="server"></asp:Label></div>

<asp:RadioButtonListID="rbAnswer"Runat="server"></asp:RadioButtonList>

<asp:CheckBoxListID="cbAnswer"Runat="server"></asp:CheckBoxList>

<asp:TextBoxID="txtAnswer"runat="server"></asp:TextBox>

</div>

</ItemTemplate>

</asp:Repeater>

<divclass="button">

<asp:ButtonID="btnSubmit"runat="server"Text="Submit"OnClick="btnSubmit_Click"/>

</div>

</div>

</form>

</body>

</html>


i appreciate your reply.
but may i know how to resolve :
Line 293: questions.Rows.Add(2, "What's your name?", "TextBox");
its appeared when i try to run your script.


Hi,

cchiuyi wrote:

Line 293: questions.Rows.Add(2, "What's your name?", "TextBox");
its appeared when i try to run your script.

Which is the error message corresponding to this line?

sorry that i forgotten to append the error message as well. the error message and its description is as below.
Description:Anerror occurred during the compilation of a resource required to servicethis request. Please review the following specific error details andmodify your source code appropriately.
Compiler Error Message:CS1501: No overload for method 'Add' takes '3' arguments

my .net version :Version Information: Microsoft .NET Framework Version:1.1.4322.2032; ASP.NET Version:1.1.4322.2032
the exact file taht i used to run could be found athttp://www.valenhsu.com/NewFile.aspx

Hi,

sorry, I've coded the Page using the .NET framework 2.0 and didn't notice a change in the Add() method of the DataRowCollection class, fromAdd(object[] values) in v1.1 toAdd(params object[] values) in v2.0

However, to make the example work on .NET v1.1, you have to replace the PopulateTable() method with this one:

private void PopulateTables()

{

questions.Rows.Add(new object[]{2, "What's your name?", "TextBox"});

questions.Rows.Add(new object[]{5, "How old are you?", "RadioButton"});

questions.Rows.Add(new object[]{7, "Where were you born?", "RadioButton"});

questions.Rows.Add(new object[]{14, "Which are your favourite web controls?", "CheckBox"});

answers.Rows.Add(new object[]{5, "5"});

answers.Rows.Add(new object[]{5, "10"});

answers.Rows.Add(new object[]{7, "USA"});

answers.Rows.Add(new object[]{7, "France"});

answers.Rows.Add(new object[]{14, "Repeater"});

answers.Rows.Add(new object[]{14, "GridView"});

}


c#.net:
int quid = (isAnswered) ? Int32.Parse(questionID.Value) : (int)item.DataItem;

how do i convert this line of code to vb.net ?
i'd tried online converters with result below :

Dim quidAsInteger = (IIf((isAnswered), Int32.Parse(questionID.Value),CInt(item.DataItem)))
Exception Details: System.FormatException: Input string was not in a correct format.

Dim quidAsInteger = (IIf((isAnswered), Int32.Parse(questionID.Value), (Integer)item.DataItem))
CompilerError Message: BC30287: '.'expected.

both doesn't work. i'd tried CType() too..


Hi,

try this:

Dim quid As Integer = (If isAnswered Then Int32.Parse(questionID.Value) Else CInt(item.DataItem))

or this:

Dim quid As Integer
If isAnswered Then
quid = Int32.Parse(questionID.Value)
Else
quid = CInt(item.DataItem)
End If


i had sepnt alot of time to make the translation work, but... unfortunately.. so far nohting works..
i'd tried
Dim quidAsInteger = (IIf((isAnswered), Int32.Parse(questionID.Value),CInt(item.DataItem)))
Dim quidAsInteger = (IIf((isAnswered), Int32.Parse(questionID.Value), (Integer)item.DataItem))
Dim quidAsInteger = (IIf((isAnswered), Int32.Parse(questionID.Value), CType(item.DataItem,Integer)
))
Dim quid As Integer = (If isAnswered Then Int32.Parse(questionID.Value) Else CInt(item.DataItem))
Dim quid As Integer
If isAnswered Then
quid = Int32.Parse(questionID.Value)
Else
quid = CInt(item.DataItem)
End If

all of these doesn';t work. i wonder why. is this a .net bug or what ?Sad [:(]

Hi,

cchiuyi wrote:


Dim quid As Integer = (If isAnswered Then Int32.Parse(questionID.Value) Else CInt(item.DataItem))


Dim quid As Integer
If isAnswered Then
quid = Int32.Parse(questionID.Value)
Else
quid = CInt(item.DataItem)
End If

could you post the error messages relative to these statements? At least did the C# version work?


If isAnswered Then
quid = Int32.Parse(questionID.Value)
Else
quid = CInt(item.DataItem)
End If

Exception Details: System.FormatException: Input string was not in a correct format.
-
Dim quid As Integer = IIf((isAnswered) , Int32.Parse(questionID.Value) , CType(item.DataItem, Integer))
Exception Details: System.FormatException: Input string was not in a correct format.
Stack Trace:
[FormatException: Input string was not in a correct format.]
System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +0
ASP.NewFile2_aspx.HandleQuestionItem(RepeaterItem item) +282
ASP.NewFile2_aspx.repQuestions_ItemDataBound(Object sender, RepeaterItemEventArgs e) +48 ~~~ more.
-
Dim quid As Integer = (IIf((isAnswered), Int32.Parse(questionID.Value), CInt(item.DataItem)))
Exception Details: System.FormatException: Input string was not in a correct format.
Stack Trace:
[FormatException: Input string was not in a correct format.]
System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +0
ASP.NewFile2_aspx.HandleQuestionItem(RepeaterItem item) +282
ASP.NewFile2_aspx.repQuestions_ItemDataBound(Object sender, RepeaterItemEventArgs e) +48 ~~~ more.
-
Dim quid As Integer = (IIf((isAnswered), Int32.Parse(questionID.Value), (Integer)item.DataItem))
Compiler Error Message: BC30287: '.' expected.
Source Error: Line 96: Dim quid As Integer = (IIf((isAnswered), Int32.Parse(questionID.Value), (Integer)item.DataItem))
No Stack Trace
-
Dim quid As Integer = (If isAnswered Then Int32.Parse(questionID.Value) Else CInt(item.DataItem))
Compiler Error Message: BC30201: Expression expected.
Source Error: Line 96: Dim quid As Integer = (If isAnswered Then Int32.Parse(questionID.Value) Else CInt(item.DataItem))
No Stack Trace
-
Dim quid As Integer = (IIf((isAnswered), CType(questionID.Value, Integer), CInt(item.DataItem)))
Exception Details: System.FormatException: Input string was not in a correct format.
Stack Trace:
[FormatException: Input string was not in a correct format.]
Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value, NumberFormatInfo NumberFormat) +195
Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +92
[InvalidCastException: Cast from string "" to type 'Integer' is not valid.]
Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +204
ASP.NewFile2_aspx.HandleQuestionItem(RepeaterItem item) +265
ASP.NewFile2_aspx.repQuestions_ItemDataBound(Object sender, RepeaterItemEventArgs e) +48 ~~~ more.
-
Dim quid As Integer = (IIf((isAnswered), CInt(questionID.Value), CInt(item.DataItem)))
Exception Details: System.FormatException: Input string was not in a correct format.
Stack Trace:
[FormatException: Input string was not in a correct format.]
Microsoft.VisualBasic.CompilerServices.DoubleType.Parse(String Value, NumberFormatInfo NumberFormat) +195
Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +92
[InvalidCastException: Cast from string "" to type 'Integer' is not valid.]
Microsoft.VisualBasic.CompilerServices.IntegerType.FromString(String Value) +204
ASP.NewFile2_aspx.HandleQuestionItem(RepeaterItem item) +265
ASP.NewFile2_aspx.repQuestions_ItemDataBound(Object sender, RepeaterItemEventArgs e) +48 ~~~ more.

C#.NET's Code works without any errors.
tried online c#.net to vb.net translator too (above).



Hi,

the following is theVB.NET version of the questionary example.

I had to correct the IIf statement and convert the string concatenation operator from '+' (used in C#) to '&' (used in VB.NET).

<%@.PageLanguage="vb" %>

<%@.ImportNamespace="System.Data" %>

<scriptrunat="server">

Protected questions As DataTable

Protected answers As DataTable

Protected isAnswered As Boolean = False

Private Sub Page_Load(sender As Object, e As EventArgs)

' Build the data structure and insert data used

' in this example.

BuildTables()

PopulateTables()

If Not Page.IsPostBack Then

' Bind the question Repeater with a list

' of question IDs.

Dim quids As New ArrayList()

Dim row As DataRow

For Each row In questions.Rows

quids.Add(row("ID"))

Next row

repQuestions.DataSource = quids

repQuestions.DataBind()

End If

End Sub 'Page_Load

' This method handles the ItemDataBound event of the question Repeater.

' It calls HandleQuestionItem passing a repeater item as an argument.

Private Sub repQuestions_ItemDataBound(sender As Object, e As RepeaterItemEventArgs)

Select Case e.Item.ItemType

Case ListItemType.Item, ListItemType.AlternatingItem

HandleQuestionItem(e.Item)

Case Else

End Select

End Sub 'repQuestions_ItemDataBound

' This method handles a question represented by a Repeater item.

' The flag isAnswered is used to determine if the questionary

' has been answered.

Private Sub HandleQuestionItem(item As RepeaterItem)

' Get references to the controls contained in this item.

Dim questionID As HtmlInputHidden = CType(item.FindControl("questionID"), HtmlInputHidden)

Dim lblText As Label = CType(item.FindControl("lblText"), Label)

Dim rbAnswer As RadioButtonList = CType(item.FindControl("rbAnswer"), RadioButtonList)

Dim cbAnswer As CheckBoxList = CType(item.FindControl("cbAnswer"), CheckBoxList)

Dim txtAnswer As TextBox = CType(item.FindControl("txtAnswer"), TextBox)

' Retrieve the question ID, its type and its text.

Dim quid As Integer

If isAnswered Then

quid = Int32.Parse(questionID.Value)

Else

quid = CInt(item.DataItem)

End If

Dim qtype As String = CStr(questions.Select(("ID = " & quid))(0)("Type"))

Dim qtext As String = CStr(questions.Select(("ID = " & quid))(0)("Text"))

' If we are generating questions, fill the questionID field and

' the label that holds the question's text.

If Not isAnswered Then

questionID.Value = Convert.ToString(quid)

lblText.Text = qtext

End If

' Take action based on the type of question.

Select Case qtype

Case "RadioButton"

' If answered, output a string with the answer.

If isAnswered Then

Response.Write(("Answer to question " & questionID.Value & ": " & rbAnswer.SelectedValue & "<br />"))

Else

' This is an example of binding a ListControl without using

' the DataBind() method.

Dim rbAns As DataRow() = answers.Select(("QuestionID =" & quid))

Dim ans As DataRow

For Each ans In rbAns

Dim ansText As String = CStr(ans("Text"))

rbAnswer.Items.Add(New ListItem(ansText, ansText))

Next ans

' This question doesn't need a TextBox to be displayed.

txtAnswer.Visible = False

End If

Case "CheckBox"

If isAnswered Then

Response.Write(("Answers for question " & questionID.Value & ": "))

Dim cb As ListItem

For Each cb In cbAnswer.Items

If cb.Selected Then

Response.Write((cb.Value & " "))

End If

Next cb

Response.Write("<br>")

Else

' Same as for the RadioButton case.

Dim cbAns As DataRow() = answers.Select(("QuestionID =" & quid))

Dim ans As DataRow

For Each ans In cbAns

Dim ansText As String = CStr(ans("Text"))

cbAnswer.Items.Add(New ListItem(ansText, ansText))

Next ans

txtAnswer.Visible = False

End If

Case "TextBox"

' To display only the TextBox, just leave the ListControls

' unbound.

If isAnswered Then

Response.Write(("Answer to question " & questionID.Value & ": " & txtAnswer.Text & "<br>"))

End If

Case Else

End Select

End Sub 'HandleQuestionItem

Private Sub btnSubmit_Click(sender As Object, e As EventArgs)

' The questionary has been submitted and it is

' considered answered.

isAnswered = True

' Loop through the Repeater items to get answers.

Dim item As RepeaterItem

For Each item In repQuestions.Items

HandleQuestionItem(item)

Next item

End Sub 'btnSubmit_Click

' Data used in this example.

Private Sub PopulateTables()

questions.Rows.Add(New Object() {2, "What's your name?", "TextBox"})

questions.Rows.Add(New Object() {5, "How old are you?", "RadioButton"})

questions.Rows.Add(New Object() {7, "Where were you born?", "RadioButton"})

questions.Rows.Add(New Object() {14, "Which are your favourite web controls?", "CheckBox"})

answers.Rows.Add(New Object() {5, "5"})

answers.Rows.Add(New Object() {5, "10"})

answers.Rows.Add(New Object() {7, "USA"})

answers.Rows.Add(New Object() {7, "France"})

answers.Rows.Add(New Object() {14, "Repeater"})

answers.Rows.Add(New Object() {14, "GridView"})

End Sub 'PopulateTables

Private Sub BuildTables()

questions = New DataTable("Questions")

questions.Columns.Add(New DataColumn("ID", GetType(Integer)))

questions.Columns.Add(New DataColumn("Text", GetType(String)))

questions.Columns.Add(New DataColumn("Type", GetType(String)))

answers = New DataTable("Answers")

answers.Columns.Add(New DataColumn("QuestionID", GetType(Integer)))

answers.Columns.Add(New DataColumn("Text", GetType(String)))

End Sub 'BuildTables

</script>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server"ID="Head1">

<title>Untitled Page</title>

<styletype="text/css">

.container{width:80%;margin:auto;}

.question {width:90%;margin:auto;border:outset1px;padding:3px;margin-bottom:10px;}

.button{width:90%;margin:auto;text-align:left;}

</style>

</head>

<body>

<formid="form1"runat="server">

<divclass="container">

<asp:RepeaterID="repQuestions"Runat="server"

OnItemDataBound="repQuestions_ItemDataBound">

<ItemTemplate>

<divclass="question">

<inputtype="hidden"id="questionID"runat="server"NAME="questionID"/>

<div><asp:LabelID="lblText"runat="server"></asp:Label></div>

<asp:RadioButtonListID="rbAnswer"Runat="server"></asp:RadioButtonList>

<asp:CheckBoxListID="cbAnswer"Runat="server"></asp:CheckBoxList>

<asp:TextBoxID="txtAnswer"runat="server"></asp:TextBox>

</div>

</ItemTemplate>

</asp:Repeater>

<divclass="button">

<asp:ButtonID="btnSubmit"runat="server"Text="Submit"OnClick="btnSubmit_Click"/>

</div>

</div>

</form>

</body>

</html>

Wednesday, March 21, 2012

populating a drop down list with information from a database

Hello,
I am using C# and want to dynamically populate a drop down list with information from my database. I can do this effectively by data binding to the drop down list.

customerInfo.DataSource = aDataSet;
customerInfo.DataValueField = "licence_No";
customerInfo.DataTextField = "licence_No";
customerInfo.DataBind();

customer.Info is the name of my DDL. This does populate my DDL. However there is a big problem. If I try and get the selectedItem value from the DDL it is always equal to the first item in DDL, and therefore my DDL is useless.
Any suggestions, its been causing me alot of problems.Post the code you are using to get the selectedItem. Also, where in your code are you trying to get the selectedItem - after a certain event? When is the DropDownList populated? It probably should be populated once, when ! Page.IsPostBack()...

cjmaxey
The code I am using to get the selected item is:


string selection = customerInfo.SelectedItem.ToString();

I am trying to get the selected item when a button is clicked. The drop down list is populated on page load.
Thanks for the help.
shannon_rider,

Be sure that the Dropdownlist is populated within Page_Load() within the following:


if ( ! Page.IsPostBack() )
{
// populate database
} // end if - Not Page PostBack

It may be that that the DropDownList is getting re-populated before the SelectedItem is found and, therefore, being reset to the first item.

Also, you may want to use one of the following depending on whether you want the text or the value (in your case, I believe they are the same):


string selection = customerInfo.SelectedItem.Value.ToString();
string selection = customerInfo.SelectedItem.Text.ToString();

Hope this helps,

cjmaxey
Thanks,
That advice has worked. I appreciate you taking the time to help.
I'll take that lesson on board.

Friday, March 16, 2012

Populating Controls - Form Load Dynamically

hi all,
how can I populate one aspx form when page is loading based on page ID? for
example:
loading page A (to search for VB code) would display labels and texboxes,
dropdown lists all related to VB, plus the address bar would show something
like this: www.somethinghere?id=3
and if you change number 3 from the address bar to (for example) 34 or 71
you would get different page with the same formatting like I.e:
www.somethinghere?id=34 would load the page related to C# topics and all
labels and texboxes and dropdown lists related to C# OR
www.somethinghere?id=71 would load the page related to ASP.NET for example
and labels and textboxes would be populated according to ASP.NET and so
on...

my question is, how do they do that? they must assign an ID number for each
topic but then how they populate all controls on that ONE page accordingly?

I am very much interested in this approach and wants to know how its done
and how can I get more info about it. I think its better than duplicating
pages if you were going to use them over and over?

what do you think?

please let me know

thanksid=XX part of the url is available as Request.QueryString.
Request.QueryString["id"] for www.somethinghere?id=71 will return "71".
PageLoad event code can read the id and setup the page controls accordingly.

--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]

"netasp" <netasp@.newsgroups.nospamwrote in message
news:O6fQ523xGHA.3488@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

hi all,
how can I populate one aspx form when page is loading based on page ID?
for example:
loading page A (to search for VB code) would display labels and texboxes,
dropdown lists all related to VB, plus the address bar would show
something like this: www.somethinghere?id=3
>
and if you change number 3 from the address bar to (for example) 34 or 71
you would get different page with the same formatting like I.e:
www.somethinghere?id=34 would load the page related to C# topics and all
labels and texboxes and dropdown lists related to C# OR
www.somethinghere?id=71 would load the page related to ASP.NET for example
and labels and textboxes would be populated according to ASP.NET and so
on...
>
my question is, how do they do that? they must assign an ID number for
each topic but then how they populate all controls on that ONE page
accordingly?
>
I am very much interested in this approach and wants to know how its done
and how can I get more info about it. I think its better than duplicating
pages if you were going to use them over and over?
>
what do you think?
>
please let me know
>
thanks
>
>


thanks Eliyahu for your reply,

does this method considered to be a good or bad practice with visual studio
2005? because I also have seen some other web applications using different
pages for each category page, their address bar would show aspx pages I.e
employee.aspx, manager.aspx, supervisor.aspx instead of loading everything
into one template page.

I just want to know what is the best practice and recommendation for such a
scenario?

thanks again

"Eliyahu Goldin" <REMOVEALLCAPITALSeEgGoldDinN@.mMvVpPsS.orgwrote in
message news:%23mXBFJ5xGHA.4732@.TK2MSFTNGP03.phx.gbl...

Quote:

Originally Posted by

id=XX part of the url is available as Request.QueryString.
Request.QueryString["id"] for www.somethinghere?id=71 will return "71".
PageLoad event code can read the id and setup the page controls
accordingly.
>
--
Eliyahu Goldin,
Software Developer & Consultant
Microsoft MVP [ASP.NET]
>
"netasp" <netasp@.newsgroups.nospamwrote in message
news:O6fQ523xGHA.3488@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

>hi all,
>how can I populate one aspx form when page is loading based on page ID?
>for example:
>loading page A (to search for VB code) would display labels and texboxes,
>dropdown lists all related to VB, plus the address bar would show
>something like this: www.somethinghere?id=3
>>
>and if you change number 3 from the address bar to (for example) 34 or 71
>you would get different page with the same formatting like I.e:
>www.somethinghere?id=34 would load the page related to C# topics and all
>labels and texboxes and dropdown lists related to C# OR
>www.somethinghere?id=71 would load the page related to ASP.NET for
>example and labels and textboxes would be populated according to ASP.NET
>and so on...
>>
>my question is, how do they do that? they must assign an ID number for
>each topic but then how they populate all controls on that ONE page
>accordingly?
>>
>I am very much interested in this approach and wants to know how its done
>and how can I get more info about it. I think its better than duplicating
>pages if you were going to use them over and over?
>>
>what do you think?
>>
>please let me know
>>
>thanks
>>
>>


>
>


Hello Netasp,

In ASP.NET, dynamically creating webcontrols is naturally supported. Here
are some web articles introducing this:

#HOW TO: Dynamically Create Controls in ASP.NET by Using Visual C# .NET
http://support.microsoft.com/kb/317794/EN-US/
#Adding Controls to a Web Forms Page Programmatically
http://authors.aspalliance.com/aspx...dingcontrolstow
ebformspageprogrammatically.aspx

#How to: Add Controls to an ASP.NET Web Page Programmatically
http://msdn2.microsoft.com/en-us/library/kyt0fzt1.aspx
for your scenario, you want to generate two page UI for different client
user requests(search for VB or c#), I think you need to consider the
following things:

Which one is more important for our application, flexibiilty or
performance?

When we dynamically create the page UI depend on different client requests,
it make the page very flexible and easy to extend when you want to add
additional UI template(such as search for J#...). However, the drawback
here is that dynamically creating control will add performance overhead
which is less efficient than statically compiled and loaded page/controls.
Also, making the page UI dynamically generated will make the line of code
in your page increase significantly.

IMO, for those pages which as definitely different code logic and business
purpose or the UI differ from each other obviously, I would recommend you
create separate page for each one.

If the UI of those pages are similar and easy to be templated, you can
consider creating a page to dynamically generate UI.

Please feel free to let me know if you have any further questions.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.
thank you Steven for your reply,

how about this:
I create the page and add all the necessary controls to it, dropdown list,
an image box, labels and some textboxes (with generic names) -// so there is
not an overhead of creating controls dynamically

then, if the user clicks the ASP.NET link for example (and lets say it has
been assigned ID=1) then I go to my database and load the appropriate
control names and images for the C# page! OR if the user clicks C# link
(which lets also assume it has been assigned to ID=21) then I will load from
another table all the appropriate names for labels, textboxes and images for
that C# page.

what do you think? would that cut half of my overhead expenses? considering
the controls are already been created?

I would love to hear your input on this approach.

thank you very much for the links

"Steven Cheng[MSFT]" <stcheng@.online.microsoft.comwrote in message
news:hp8bsa$xGHA.4220@.TK2MSFTNGXA01.phx.gbl...

Quote:

Originally Posted by

Hello Netasp,
>
In ASP.NET, dynamically creating webcontrols is naturally supported. Here
are some web articles introducing this:
>
#HOW TO: Dynamically Create Controls in ASP.NET by Using Visual C# .NET
http://support.microsoft.com/kb/317794/EN-US/
>
#Adding Controls to a Web Forms Page Programmatically
http://authors.aspalliance.com/aspx...dingcontrolstow
ebformspageprogrammatically.aspx
>
#How to: Add Controls to an ASP.NET Web Page Programmatically
http://msdn2.microsoft.com/en-us/library/kyt0fzt1.aspx
>
for your scenario, you want to generate two page UI for different client
user requests(search for VB or c#), I think you need to consider the
following things:
>
Which one is more important for our application, flexibiilty or
performance?
>
When we dynamically create the page UI depend on different client
requests,
it make the page very flexible and easy to extend when you want to add
additional UI template(such as search for J#...). However, the drawback
here is that dynamically creating control will add performance overhead
which is less efficient than statically compiled and loaded page/controls.
Also, making the page UI dynamically generated will make the line of code
in your page increase significantly.
>
IMO, for those pages which as definitely different code logic and business
purpose or the UI differ from each other obviously, I would recommend you
create separate page for each one.
>
If the UI of those pages are similar and easy to be templated, you can
consider creating a page to dynamically generate UI.
>
Please feel free to let me know if you have any further questions.
>
>
Sincerely,
>
Steven Cheng
>
Microsoft MSDN Online Support Lead
>
>
>
This posting is provided "AS IS" with no warranties, and confers no
rights.
>


Thanks for your reply Netasp,

As for the new idea you mentioned, do you mean you predefine all the
controls on the page and assigned fixed ID for each one. and dynamically
load their string resources( such as Text ...) from file or database and
assign to their "Text" property? If this is the case, I think it doable.

Of course, if the controls are defined at design-time, it will save lots of
dynamic control creating and loading overhead.

Please let me know if you have any further questions.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.
thanks Steven for your reply,

yeah, this is very much the idea, and I think its better than creating more
than one aspx page that does exactly the same thing.

it seems doable so far, and I will pick up any issues as I advance.

thanks for your help.

best regard,

"Steven Cheng[MSFT]" <stcheng@.online.microsoft.comwrote in message
news:9Q8DZ2nyGHA.4616@.TK2MSFTNGXA01.phx.gbl...

Quote:

Originally Posted by

Thanks for your reply Netasp,
>
As for the new idea you mentioned, do you mean you predefine all the
controls on the page and assigned fixed ID for each one. and dynamically
load their string resources( such as Text ...) from file or database and
assign to their "Text" property? If this is the case, I think it doable.
>
Of course, if the controls are defined at design-time, it will save lots
of
dynamic control creating and loading overhead.
>
Please let me know if you have any further questions.
>
Sincerely,
>
Steven Cheng
>
Microsoft MSDN Online Support Lead
>
>
This posting is provided "AS IS" with no warranties, and confers no
rights.
>
>


Thanks for the followup Netasp,

Yes, this is a good idea. Actually, what you do is just how ASP.NET
application do localization support for web pages. ASP.NET support creating
resource files for each page or the whole application and we can load
string or other resource(like image, files) from resource file according
different CultureInfo. So for your case here, instead of depending on
CultureInfo, your page's resource are depend on other criteria.

Please feel free to post here if you meet any further problem.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.
now I have one final question,
what is the best reliable way of loading a control value from a database?
lets say I have label1 already sitting in my webform how can I load its
content "Books" from a table1 in sql 2005 database?

do I use a normal adapter to loop through? is there a good examples
illustrating how to accomplish that?

thanks
"netasp" <netasp@.newsgroups.nospamwrote in message
news:%235MSXCtyGHA.284@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

thanks Steven for your reply,
>
yeah, this is very much the idea, and I think its better than creating
more than one aspx page that does exactly the same thing.
>
it seems doable so far, and I will pick up any issues as I advance.
>
thanks for your help.
>
best regard,
>
"Steven Cheng[MSFT]" <stcheng@.online.microsoft.comwrote in message
news:9Q8DZ2nyGHA.4616@.TK2MSFTNGXA01.phx.gbl...

Quote:

Originally Posted by

>Thanks for your reply Netasp,
>>
>As for the new idea you mentioned, do you mean you predefine all the
>controls on the page and assigned fixed ID for each one. and dynamically
>load their string resources( such as Text ...) from file or database
>and
>assign to their "Text" property? If this is the case, I think it
>doable.
>>
>Of course, if the controls are defined at design-time, it will save lots
>of
>dynamic control creating and loading overhead.
>>
>Please let me know if you have any further questions.
>>
>Sincerely,
>>
>Steven Cheng
>>
>Microsoft MSDN Online Support Lead
>>
>>
>This posting is provided "AS IS" with no warranties, and confers no
>rights.
>>
>>


>
>


Hi Netasp,

how you'll read the static data from database depend on how will you use
them. If you will only load them at each page's startup time and will
requrey database if require them later, I suggest you use Sqlcommand +
DataReader to query the data since this will have better performance.

If you will load the data and also cached them in local memory for later
use, you can consider use TableAdpater and return them in the form of
DataTable, Dataset ...

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

This posting is provided "AS IS" with no warranties, and confers no rights.