The question may be a bit long :
I am making an Online Evaluation Portal and there different type of questions in database which needs to be loaded in the web- form. The questions can be Single Answer(radio button) or multi-answer(check box button). So depending upon the type I create the radio button or check box as per requirement and load it in the Repeater during Runtime. The code is as below :
SqlCommand cmd = new SqlCommand("select * from tbl_QuestionAnswer", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer1";
rAnswer1.GroupName = "QAnswer1";
rAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(rAnswer1);
RadioButton rAnswer2 = new RadioButton();
rAnswer2.ID = "rbl_Answer2";
rAnswer2.GroupName = "QAnswer1";
rAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(rAnswer2);
RadioButton rAnswer3 = new RadioButton();
rAnswer3.ID = "rbl_Answer3";
rAnswer3.GroupName = "QAnswer1";
rAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(rAnswer3);
RadioButton rAnswer4 = new RadioButton();
rAnswer4.ID = "rbl_Answer4";
rAnswer4.GroupName = "QAnswer1";
rAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(rAnswer4);
}
else
{
CheckBox cAnswer1 = new CheckBox();
cAnswer1.ID = "chk_Answer1";
cAnswer1.Text = dr["Answer1"].ToString();
Panel PAnswer1 = e.Item.FindControl("PAnswer1") as Panel;
PAnswer1.Controls.Add(cAnswer1);
CheckBox cAnswer2 = new CheckBox();
cAnswer2.ID = "chk_Answer2";
cAnswer2.Text = dr["Answer2"].ToString();
Panel PAnswer2 = e.Item.FindControl("PAnswer2") as Panel;
PAnswer2.Controls.Add(cAnswer2);
CheckBox cAnswer3 = new CheckBox();
cAnswer3.ID = "chk_Answer3";
cAnswer3.Text = dr["Answer3"].ToString();
Panel PAnswer3 = e.Item.FindControl("PAnswer3") as Panel;
PAnswer3.Controls.Add(cAnswer3);
CheckBox cAnswer4 = new CheckBox();
cAnswer4.ID = "chk_Answer4";
cAnswer4.Text = dr["Answer4"].ToString();
Panel PAnswer4 = e.Item.FindControl("PAnswer4") as Panel;
PAnswer4.Controls.Add(cAnswer4);
}
}
But the problem here is all the answers get loaded in all questions. i.e. from that dr["Answer1"] it takes all the data in the "Answer1" column and then makes a check-box or radio-button. I don't know why that is happening as it should take only onr row at a time and data from that row only.
Also this runs good till 2 questions. After that if I add 3rd question and try to load it, it gives error saying "Multiple controls with the same ID 'rbl_Answer1' were found. FindControl requires that controls have unique IDs.". And this is correct too. So I need a approach to load questions into the web-form dynamically depending on Single answer or multi -asnwer
It's very clear that you may create control with the same id if you have more than one row in your query.
Try to make dynamic field/control and set dynamic ID for those control
while (dr.Read())
{
if ((string)dr["type"] == "SingleAnswer")
{
RadioButton rAnswer1 = new RadioButton();
rAnswer1.ID = "rbl_Answer" + dr["AnswerID1"].ToString();
or something like that...
Related
im working on a project(UWP C sharp) from college..
i need to build library program that manege books and magazines
i have a problem with the edit item page...
iv created method that create elements (text box, datepicker , etc..) dynamically by the type of the item that selected (if the user select book, he'll get the elements for book same for magazines..)
the problem is when im trying to write the event button that take the values from all those elements i cant reach them... cuz they in a method..
(like book.title = textbox.text;)
sorry for my English and Ty for the help:)
private void CreateBtnsByTheTypeOfTheItem(AbstractItem item)
{
TextBox editTitleTB = new TextBox();
editTitleTB.Text = LibManager.Instance.CurrentItem.Title;
Grid.SetRow(editTitleTB, 0);
editPageGrid.Children.Add(editTitleTB);
CheckBox editIsAvaibleCB = new CheckBox();
editIsAvaibleCB.Content = "Is Avaible";
editIsAvaibleCB.IsChecked = item.isAvaible;
Grid.SetRow(editIsAvaibleCB, 1);
editPageGrid.Children.Add(editIsAvaibleCB);
DatePicker editDatePicler = new DatePicker();
editDatePicler.Date = item.PublishDate;
Grid.SetRow(editDatePicler, 3);
editPageGrid.Children.Add(editDatePicler);
if (item is Book)
{
Book itemAsBook = item as Book;
TextBox editAuthor = new TextBox();
editAuthor.Text = itemAsBook.Author;
Grid.SetRow(editAuthor, 2);
editPageGrid.Children.Add(editAuthor);
var _enumval = Enum.GetValues(typeof(BookCategory)).Cast<BookCategory>();
ComboBox editCategpryCB = new ComboBox();
editCategpryCB.ItemsSource = _enumval.ToList();
editCategpryCB.SelectedItem = itemAsBook.Category;
Grid.SetRow(editCategpryCB, 4);
editPageGrid.Children.Add(editCategpryCB);
}
else
{
Magazine itemAsMagazine = item as Magazine;
TextBox editEditors = new TextBox();
editEditors.Text = itemAsMagazine.Editors;
Grid.SetRow(editEditors, 2);
editPageGrid.Children.Add(editEditors);
var _enumval = Enum.GetValues(typeof(MagazineCategory)).Cast<MagazineCategory>();
ComboBox editMagazineCategory = new ComboBox();
editMagazineCategory.ItemsSource = _enumval.ToList();
editMagazineCategory.SelectedItem = itemAsMagazine.Category;
Grid.SetRow(editMagazineCategory, 4);
editPageGrid.Children.Add(editMagazineCategory);
}
If you have named each of the dynamically created field you can access them by using the FindName method.
TextBox editTitleTB = new TextBox();
editTitleTB.Name = "TheHobbitTB";
editTitleTB.Text = LibManager.Instance.CurrentItem.Title;
TextBox theHobbitTB = (TextBox)this.FindName("TheHobbitTB");
Then you could essentially edit what ever you want about this specific textbox.
I'm trying to add a new Control to AvalonDock from code.
Here`s the code:
var test = new LayoutAnchorable();
test.Title = "teste";
test.IsActive = true;
test.IsSelected = true;
test.ContentId = "search12";
test.Content = new TextBox();
test.AddToLayout(dockingManager, AnchorableShowStrategy.Right);
The new panel shows up, but the Content doesn't (just gray panel).
Why?
I know this is a well asked question and I found some marked as answers but those doesn't solve my problem. Please have a look at my codes..
Method to Display dynamic controls
private void ShowControlsByFormId()
{
List<FormControlsBO> list = new List<FormControlsBO>();
list = new FormControlsDA().FormControls_GetByFormId(Convert.ToInt32(ddlForm.SelectedValue.ToString()));
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
DynamicControl dynamicControl = CommonUtility.GenerateControl(list[i]);
pnlInput.Controls.Add(new LiteralControl("<tr><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControlLiteral);
pnlInput.Controls.Add(new LiteralControl("</td><td></td><td>"));
pnlInput.Controls.Add(dynamicControl.GeneratedControl);
pnlInput.Controls.Add(new LiteralControl("</td><tr><br/><br/>"));
}
pnlAction.Visible = true;
}
else
{
pnlAction.Visible = false;
}
}
Method to Generate dynamic controls
public static DynamicControl GenerateControl(FormControlsBO bo)
{
DynamicControl dynamicControl = new DynamicControl();
Control control = new Control();
LiteralControl literal = new LiteralControl();
switch (bo.FieldType)
{
case "TextBox":
control = new TextBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "RadioButton":
control = new RadioButton();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "CheckBox":
control = new CheckBox();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
case "DropDownList":
control = new DropDownList();
control.ID = bo.FieldName;
literal.Text = bo.FieldLabel;
break;
}
control.ClientIDMode = ClientIDMode.Static;
dynamicControl.GeneratedControl = control;
dynamicControl.GeneratedControlLiteral = literal;
return dynamicControl;
}
Method to Save data
private void FormRecords_Save()
{
List<FormControlsBO> list = new List<FormControlsBO>();
FormControlsBO bo = new FormControlsBO();
foreach (Control ctl in pnlInput.Controls)
{
CommonUtility.DataFiller(bo, ctl);
list.Add(bo);
}
Boolean result = false;
result = new FormControlsDA().FormRecords_Save(list);
if(result == true)
{
lblMessage.Text = "Form data saved successfully";
}
else
{
lblMessage.Text = "Form data not saved";
}
}
The problem is, when I debug the code, pnlInput.Controls shows Zero count. Please help !!
As I already answered here all dynamic controls should be reinitiated in Page's Init event, as viewstate manager values are set every request. You can check page's lifecycle.
So right now, when you do not create you control in init event, viewstates misses them while it is setting postback data, and when you do try to get values, they are equal to zeros.
Keep in mind, that you have to create the same control types with the same names.
If you have written the code to generate Dynamic Controls and if it is in the page load event use FindControl("IdofControl"); to retrive its value;
For Example,
TextBox txtInstance = (TextBox)FindControl("IdofControl");
string txtvalueinTextBox =txtInstance.Text;
Make sure that the controls are dynamically generated in all page reloads.If the controls generated on the postback is different the viewState may not restore back properly.
Im working on a project just to add few things and one of thoose is to add a DropDownList on a GridView when they press the edit button of a row... Sadly the columns are added on runtime before the database binding, not on the aspx page as all the examples i found, i have it here like this:
private void SetColumnsGrid(GridView Grid)
{
BoundField Col = new BoundField();//1
Col.HeaderText = "Name";
Col.DataField = "Name";
Col.HeaderStyle.Width = Unit.Pixel(100);
Col.ReadOnly = true;
Grid.Columns.Add(Col);
Col = new BoundField(); //2
Col.HeaderText = "User Type";
Col.DataField = "UserType";
Col.HeaderStyle.Width = Unit.Pixel(100);
Grid.Columns.Add(Col);
//Is ddl spected to be here as the TemplateField with the EditItemTemplate?
}
So, how can i do it? I just dont find the proper way.
Whitch events should i handle?
Thank you very much
There are several options you can use. One is to use a template, the other is to manually add the control when the row is created. Template example (this uses a checkbox but can easily be switched):
Public Class CheckBoxTemplate
Implements ITemplate
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Dim cb As CheckBox = New CheckBox()
cb.ID = "someId"
cb.AutoPostBack = True
container.Controls.Add(cb)
End Sub
End Class
In your app code, where you create the gridview control:
Dim gv As New GridView
With gv
.ID = "myGridView"
.AutoGenerateColumns = False
.DataKeyNames = New String() {"somePKID"}
.GridLines = GridLines.Both
.AllowSorting = False
.AllowPaging = False
.PageSize = numRows
.Width = tableWidth
.BorderColor = Drawing.ColorTranslator.FromHtml("#808080")
.PagerSettings.Mode = PagerButtons.NextPrevious
.PagerSettings.NextPageText = "Next"
.PagerSettings.PreviousPageText = "Prev"
.HeaderStyle.CssClass = foundUserHeadStyle
.RowStyle.CssClass = foundUserEvenRows
.AlternatingRowStyle.CssClass = foundUserOddRows
.Columns.Clear()
Dim SelectUserTF As New TemplateField
With SelectUserTF
.HeaderText = "Add"
.ItemStyle.Wrap = False
.ItemTemplate = New CheckBoxTemplate()
End With
.Columns.Add(SelectUserTF)
End With
Another option is to do this in the create row event:
Protected Sub gv_rowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles myGridView.RowCreated
Try
Dim myDDL As New DropDownList
Dim myCollection As New ListItemCollection
With myCollection
Dim newItem As New ListItem
newItem.Text = "item 1"
newItem.Value = "1"
.Add(newItem)
End With
e.Row.Cells(0).Controls.Add(myDDL)
Catch ex As Exception
Finally
End Try
end sub
Let me know if this helps or if you have a question about it.
I am creating an application where I require to add dynamic checkbox list. Please anyone tell me how to add dynamic checkbox list using C#.
Put a placeHolder on your form with the ID placeHolder and add the following code to your Page_Load():
CheckBoxList cbList = new CheckBoxList();
for (int i = 0; i < 10; i++)
cbList.Items.Add(new ListItem("Checkbox " + i.ToString(), i.ToString()));
placeHolder.Controls.Add(cbList);
This will add 10 CheckBox objects within your CheckBoxList(cbList).
Use the following code to examine each CheckBox object within the CheckBoxList
foreach(ListItem li in cbList.Items)
{
var value = li.Value;
var text = li.Text;
bool isChecked = li.Selected;
}
The placeholder is used to add the CheckBoxList to the form at runtime, using a placeholder will give you more control over the web page where the CheckBoxList and its items will appear.
Here is an example
CheckBoxList chkList = new CheckBoxList();
CheckBox chk = new CheckBox();
chkList.ID = "ChkUser";
chkList.AutoPostBack = true;
chkList.RepeatColumns = 6;
chkList.DataSource = us.GetUserDS();
chkList.DataTextField = "User_Name";
chkList.DataValueField = "User_Id";
chkList.DataBind();
Panel pUser = new Panel();
if (pUserGrp != "")
{
pUser.GroupingText = pUserGrp ;
chk.Text = pUserGrp;
}
else
{
pUser.GroupingText = "Non Assigned Group";
chk.Text = "Non Assigned group";
}
pUser.Controls.Add(chk);
pUser.Controls.Add(chkList);
this.Form.Controls.Add(pUser);
At code behind you can create new ASP.NET Controls and you can add these controls to your page. All you need to do is to create new CheckBoxList Object and add ListItems to it. Finally, you need to add your CheckBoxList to your Page.
// Create CheckBoxList
CheckBoxList list= new CheckBoxList();
// Set attributes for CheckBoxList
list.ID = "CheckBoxList1";
list.AutoPostBack = true;
// Create ListItem
ListItem listItem = new ListItem();
// Set attributes for ListItem
listItem .ID = "ListItem1";
// Add ListItem to CheckBoxList
list.Items.Add(listItem );
// Add your new control to page
this.Form.Controls.Add(list);