Add Dynamic cotrol to aspx Page - c#

I want to add checkbox in table heads dynamically,I have created their ids dynamically but how to print it on Aspx Page ???
<table border="1">
<thead>
<%string j = " Check"; %>
<%for (int i = 0; i < 10;i++ )
{%>
<th style="padding:2px; width:500px;">Table Head<br /><br />
<%
CheckBox chk = new CheckBox();
chk.ID = i + j;
chk.Text = "I am "+ i+j;
%>
<%=chk %>
</th>
<%} %>
</thead>
</table>

<input type="checkbox" id='<%=i%>' name="allcheck">
Use ASP.NET Web Form, please use HTML tags more, not like this :)
CheckBox chk = new CheckBox();
chk.ID = i + j;
chk.Text = "I am "+ i+j;
example:
aspx page:
<input type="hidden" id="userid" value='<%=userid>'/>
<input type="checkbox" id='<%=i%>' name="allcheck" /> with for
js code with jquery:
function delete()
var id_array = new Array();
$('input[name="allcheck"]:checked').each(function () {
id_array.push($(this).attr('id'));
});
var idstr = id_array.join(',');
$.ajax({
method:"POST",
url: "services/delete",
data: {
userid: $("#userid").val(), ids: idstr
}
})
with ashx:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Cache.SetNoStore();
string userid = "";
string ids = "";
try
{
string userid = context.Request.QueryString["userid"];
string ids = context.Request.QueryString["ids"];
//then do your things
}
catch (Exception)
{
throw;
}
}

Hopefully it can help you to deal with your problem.
Front end
<body>
<form id="form1" runat="server">
<table>
<thead id="test" runat="server">
</thead>
</table>
</form>
</body>
Back end
protected void Page_Load(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.ID="****";
test.Controls.Add(cb);
}

If you are using ASPX page then use simply any control like GirdView or DataList or Repeater.
In that you put your checkbox, it will create dynamic ID Automatically and you can easily find that control on your back end coding..
For example check below links.
http://www.asp.net/web-forms/overview/data-access/displaying-data-with-the-datalist-and-repeater/displaying-data-with-the-datalist-and-repeater-controls-vb
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.repeatlayout(v=vs.110).aspx

Related

asp.net web page, getting jQuery Accordion plugin to work with asp:Repeater control

I'm working on a asp.net project. I've been asked to create a page so site admins could add articles and everyone else could add comments under those articles.
I have 2 separate tables in my db, Articles/Comments. On page load I'm populating all the articles with their own related comments within a panel.
I've also been asked to use an accordion so all comments would display in a collapsible manner!
My problem is that only the first article shows up with collapsible comments under it, and the rest do not!
Here is my aspx page:
<%# Page Title="Ref Notes" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="RefNotes.aspx.cs" Inherits="Root.RefNotes" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:Panel ID="refNotes" CssClass="col-xs-12 data-container" runat="server">
</asp:Panel>
</asp:Content>
aspx.cs code:
public partial class RefNotes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
populateNotes();
Page.Title = "Latest Ref Notes";
}
protected void populateNotes()
{
string tag = "";
if (Request.QueryString["tag"] != null) tag = Request.QueryString["tag"];
int post = 0;
if (Request.QueryString["post"] != null) post = Int32.Parse(Request.QueryString["post"]);
MediaService.Article[] articles = Global.mediaService.GetArticles(1, 1); //gets all articles
for (int i = 0; i < articles.Length; i++)
{
if (post > 0 && articles[i].ID != post) continue;
Root.Controls.Blog.RefNotesPost p = (Root.Controls.Blog.RefNotesPost)LoadControl("~/Controls/Blog/RefNotesPost.ascx");
p.SetData(articles[i]);
refNotes.Controls.Add(p);
Root.Controls.Blog.CommentControl c = (Root.Controls.Blog.CommentControl)LoadControl("~/Controls/Blog/CommentControl.ascx");
c.SetData(articles[i].ID);
refNotes.Controls.Add(c);
}
if (articles.Length == 0)
{
Literal l = new Literal();
l.Text = "<h1>No content currently available.</h1>";
refNotes.Controls.Add(l);
}
}
}
CommentControl.ascx code:
# Control Language="C#" AutoEventWireup="true" CodeBehind="CommentControl.ascx.cs" Inherits="Root.Controls.Blog.CommentControl" %>
<div class="row">
Comments:
<asp:Panel ID="errorPanelID" runat="server" CssClass="loginbox-textbox" Visible="false" Style="margin-top: 20px;">
<div class="alert alert-danger fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-times"></i>
<asp:Label ID="errorMsgID" runat="server"></asp:Label>
</div>
</asp:Panel>
</div>
<div id="dvAccordion" style="width: auto">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<h3>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("user") + " at " + Eval("dateTime") + " says:"%>'></asp:Label></h3>
<div style="background-color: #CFDEE3">
<asp:Literal ID="lit" runat="server" Text='<%#Eval("comment")%>' Mode="Transform" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div>
Add a Comment:<br />
<asp:TextBox ID="txtComment" runat="server" Rows="5" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" OnClick="saveBtn_Click" Text="Submit " />
<asp:HiddenField runat="server" ID="articleID" Value="0" />
</div>
<script type="text/javascript">
$(function () {
$("#dvAccordion").accordion();
});
</script>
CommentControl.ascx.cs code:
public partial class CommentControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SetData(int artID)
{
Services.Comment[] comments = Global.Tools.GetComments(artID);
articleID.Value = artID.ToString();
if (comments.Length > 0)
{
Repeater1.Visible = true;
Repeater1.DataSource = comments;
Repeater1.DataBind();
}
else
{
Repeater1.Visible = false;
}
}
protected void saveBtn_Click(object src, EventArgs e)
{
AdminService.Employee emp = Global.Tools.GetEmployee(Int32.Parse(Session["eid"].ToString()));
Blog.Comment a = new Blog.Comment();
a.CommentOn = txtComment.Text;
a.CreatedBy = emp.username;
a.DatePosted = DateTime.Now;
a.isVisible = 1;
a.ArticleID = int.Parse(articleID.Value);
if (Request.QueryString["post"] != null)
{
a.ID = Int32.Parse(Request.QueryString["post"]);
}
int result = Global.Tools.CreateComment(a);
if (result <= 0)
{
errorMsgID.Text = "Failed to create comment.";
errorPanelID.Visible = true;
}
else
{
Response.Redirect("/News.aspx");
}
}
txtComment.Text = string.Empty;
}
In the CommentControl.ascx file I had set the accordion based on id (#dvAccordion). I changed it to be based on class (.dvAccordion) and that solved the issue.
So for future references: when you're on a page an "id" can only be called once but a "class" can be called multiple times!

ASP webcontrols won't show me new values

I'm working on a asp project (with C#) and i have need of a way to update files from a map (with files). I've created a asp:Content block with the following form:
<form id="editForm" runat="server">
<table class="table table-hover">
<tbody>
<tr>
<td><h4><asp:Label id="Label1" runat="server" Text="title"/></h4></td>
<td><asp:Textbox id="pageName" runat="server"/></td>
</tr>
<tr>
<td><h4><asp:Label id="Label3" runat="server" Text="pageurl"/></h4></td>
<td><asp:Textbox id="pageURL" runat="server"/></td>
</tr>
</tbody>
</table>
<div id="ckeditor_div" runat="server">>
<CKEditor:CKEditorControl ID="CKEditor1" runat="server">
</CKEditor:CKEditorControl>
</div>
<asp:Button ID="editButton" OnClick="Save" Text="save" runat="server"/>
<br>
<br>
<asp:Label id="resultLabel" runat="server" />
</form>
This asp:Content block also has a Page_Load method and a Save method.
void Page_Load(Object Sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["title"]))
{
string url = Request.QueryString["title"];
string[] htmlFile = System.IO.Directory.GetFiles(Server.MapPath("~/App_Data/"), url).Select(path => System.IO.Path.GetFileName(path)).ToArray();
//if file exists
if (htmlFile.Length > 0)
{
//get file contents
string contents = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/") + url);
//get's title
int tFirst = contents.IndexOf("<title>") + "<title>".Length;
int tLast = contents.LastIndexOf("</title>");
String nameResult = contents.Substring(tFirst, tLast - tFirst);
//get's editable code
int cFirst = contents.IndexOf("<div id='content'>") + "<div id='content'>".Length;
int cLast = contents.LastIndexOf("</div>");
String codeResult = contents.Substring(cFirst, cLast - cFirst);
//give CKEditor editable code to edit
CKEditor1.Text = codeResult;
//show page url
string sub = url.Substring(0, url.Length - 5);
pageURL.Text = sub;
pageName.Text = nameResult;
}
}
}
}
void Save(Object Sender, EventArgs e)
{
string newTitle = pageName.Text;
string newURL = pageURL.Text;
string editedURL = newURL.Replace(" ", "-");
string newCode = CKEditor1.Text;
}
When i run the page, the form get's filled with the info from the selected file. This works. After i change some values and press Save, the old, original values (the ones inserted into the .Texts on load) are returned. how can i get the new, edited values? Am i doing something wrong?
Edit: Nevermind folks. Forgot the if(!IsPostBack) loop. Now if you will excuse me i'm gonna shrivel up and cry now.

Know what radio is checked in RadioGroup (ext.net)

I dinamically add one RadioGroup into a panel (see code below)
ctrl = new Ext.Net.RadioGroup();
ctrl.ID = idPregunta.ToString();
ctrl.EnableViewState = true;
((Ext.Net.RadioGroup)ctrl).GroupName = idPregunta.ToString();
((Ext.Net.RadioGroup)ctrl).FieldLabel = pregunta;
((Ext.Net.RadioGroup)ctrl).Height = 40;
((Ext.Net.RadioGroup)ctrl).LabelAlign = LabelAlign.Top;
((Ext.Net.RadioGroup)ctrl).ColumnsNumber = respuestas.Count;
bool First = true;
int radio=1;
foreach (var r in respuestas)
{
Ext.Net.Radio rdio = new Radio();
rdio.BoxLabel = r.ToString();
rdio.Width = 100;
rdio.ID = RADIO_ID + radio.ToString();
if (First)
{
rdio.Checked = true;
First = false;
}
radio++;
((Ext.Net.RadioGroup)ctrl).Items.Add(rdio);
}
But when i try to read the checked item in code behind my group doesn't have a item
p.RespuestaSeleccionada = X.GetCmp<Ext.Net.RadioGroup>(preg.ID).CheckedItems.FirstOrDefault<Ext.Net.Radio>().BoxLabel;
so who i can know the checked item?
Thanks in advance
Really, X.GetCmp() doesn't work as expected. We will investigate. (Investigated. See EDIT below the sample.)
Though, in any way, it would not give access to a Radio's BoxLabel. X.GetCmp<> just retrieve respective values from POST, but a BoxLabel is not a submitable thing. You can get access to a Radio's InputValue (or its client id if InputValue is omitted).
For now, you can retrieve the thing direct from POST.
Example
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<script runat="server">
protected void RenderRadioGroup(object sender, DirectEventArgs e)
{
RadioGroup rg = new RadioGroup()
{
ID = "RadioGroup1",
GroupName = "RadioGroup1",
ColumnsNumber = 1,
Items =
{
new Radio() { InputValue = "Radio1", BoxLabel = "Radio1" },
new Radio() { InputValue = "Radio2", BoxLabel = "Radio2" }
}
};
rg.Render(this.Form);
}
[DirectMethod]
public void GetCheckedItems()
{
X.Msg.Alert("GetCheckedItems", Request.Params["RadioGroup1"]).Show();
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET v2 Example</title>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
<ext:Button runat="server" Text="Render a RadioGroup" OnDirectClick="RenderRadioGroup" />
<ext:Button runat="server" Text="Get CheckedItems" Handler="App.direct.GetCheckedItems();" />
</form>
</body>
</html>
EDIT
Unfortunately, X.GetCmp() can't work. It can work only if populate a created RadioGroup's Items with all its Radio created by X.GetCmp(), but it is too cumbersome. So, getting a value direct from POST looks the only appropriate solution.
These links are worth a check. same sort of questions were asked
ext-net-radiogroup-checkeditems-is-always-null
ext-radiogroup-how-to-access-the-value-of-selected-radio-button

Dynamic data entry form

I have been searching around and I am lost on how to do what I am attempting to do.
I am trying to create a form where the first column is a list of names, and the next column is all dropdown lists. The idea is that for each name the user will pic a value. Each name may require two, or three or more values. I want to create a dynamic form where a user can click add in the row and another dropdown list appears.
Ex.
"Name" | Add Button | DropDown
then when I click add...
"Name" | Add Button | DropDown | DropDown
and have it keep going.
I am able to create the form and I have it working creating the dropdown lists. The problem is that I am adding the controls on the ItemCommand of a repeater, so they must be recreated every time. Because of this I cannot find a way to keep the values selected in each dropdown, when I have to recreate them.
Typically no more than two dropdowns are required but there are a few cases where three is needed, and it could arise for more. I would like to keep this dynamic as possible.
I know that if I added the dropdown's in the page Init they would be persisted on the postback, but at least in my design the user has to click add to get another drop down.
Is there a way to capture the data from these dropdowns then reload them every time? Or a better way to achieve this functionality?
Thank You for your help.
Here is some of the asp and code behind that I am using. This is functioning as I wish, but I don't know how to keep the data on a postback, as all of the dropdown lists I add are lost.
ASP:
<table>
<asp:Repeater ID="repChemicals" runat="server" OnItemCommand="repChemicals_OnItemCommand">
<ItemTemplate>
<tr>
<td>
<asp:HiddenField ID="hfNumber" runat="server" />
<%# Eval("ChemicalName") %>
</td>
<td>
<asp:Button runat="server" ID="btnAdd" Text="Add" CommandArgument="ADD" />
</td>
<td>
<div id="divContainer" runat="server">
<asp:DropDownList runat="server" Width="60px" ID="ddlTest"></asp:DropDownList>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Chem> Chemicals = new List<Chem>();
Random rnd = new Random();
for (int z = 0; z <= 10; z++)
{
List<string> t = new List<string>();
Chem a = new Chem()
{
ChemicalName = "Chemical" + z.ToString()
};
Chemicals.Add(a);
}
repChemicals.DataSource = Chemicals;
repChemicals.DataBind();
}
}
public void repChemicals_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
int number = 0;
foreach (RepeaterItem i in repChemicals.Items)
{
HiddenField hf = (HiddenField)repChemicals.Items[i.ItemIndex].FindControl("hfNumber");
if (i.ItemIndex == e.Item.ItemIndex)
{
if (!string.IsNullOrWhiteSpace(hf.Value))
{
number = Convert.ToInt16(hf.Value) + 1;
}
else
{
number = 1;
}
hf.Value = number.ToString();
}
else
{
if (!string.IsNullOrWhiteSpace(hf.Value))
{
number = Convert.ToInt16(hf.Value);
}
else
{
number = 0;
}
}
for (int x = 0; x < number; x++)
{
DropDownList ddl = new DropDownList();
ddl.Style.Add("width", "60px");
ddl.ID = "ddl" + i.ToString() + x.ToString();
ddl.Style.Add("Margin-right", "3px");
ddl.Attributes.Add("runat", "server");
ddl.DataSource = DataSource();
ddl.DataBind();
Control c = repChemicals.Items[i.ItemIndex].FindControl("divContainer");
c.Controls.Add(ddl);
}
}
Some of the loops are for creating test data. Basically I am storing a number of dynamic controls on each row in a hiddenfield. Then on the item command I loop through all of the rows and recreate all of the previously existing ddl's, and add one to the row that teh command came from.
This isn't exactly answering your question, but it accomplishes your ultimate goal in a less complex way and one that takes advantage of built in ASP.NET controls so maintaining state between postbacks is taken care of for you.
It utilizes jQuery, jQuery UI and a DropDownChecklist plugin.
ASPX
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/ui.dropdownchecklist.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/base/jquery-ui.css"/>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<asp:Repeater ID="repChemicals" runat="server">
<ItemTemplate>
<tr>
<td>
<%# Container.DataItem %>
</td>
<td>
<div id="divContainer" runat="server">
<asp:ListBox ID="lstAttributes" SelectionMode="Multiple" runat="server"></asp:ListBox>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:Button ID="btnPostback" Text="Postback" runat="server"/>
</div>
</form>
</body>
</html>
C#
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PersonAttributes
{
public partial class People : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
repChemicals.ItemCreated += RepChemicalsOnItemCreated;
var chemicals = new[] {"Hydrogen", "Helium", "Lithium", "Beryllium", "Boron"};
if(!IsPostBack)
{
repChemicals.DataSource = chemicals;
repChemicals.DataBind();
}
var dropDownChecklist = "$(document).ready(function () { $('select').dropdownchecklist(); });";
ScriptManager.RegisterStartupScript(this,GetType(),"initDropDownChecklist",dropDownChecklist,true);
}
private void RepChemicalsOnItemCreated(object sender, RepeaterItemEventArgs repeaterItemEventArgs)
{
var lst = repeaterItemEventArgs.Item.FindControl("lstAttributes") as ListBox;
if (lst == null)
return;
lst.DataSource = new[] {"Option 1", "Option 2", "Option 3"};
}
}
}
See it in action at CodeRun.

textBox ontextChanged not firing when user adds text

I am creating a textBox within a repeater like this ( so there are many textboxes created inside a loop and added to the repeater control)
.aspx.cs
TextBox textBox = new TextBox();
textBox.TextChanged += new EventHandler(textBox_TextChanged);
and I have a function like this for changing the textBox background color to white if that textbox has some text(it is yellow on creation of the form)
protected void textBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox.Text != String.Empty)
{
textBox.BackColor = System.Drawing.Color.White;
}
}
but the function doesn't seem to be hit at all. Any pointers on what I am doing wrong?
Thanks.
I would suggest to save the round trip to the server and do it with javascript. When you create your control in the code behind add the onchange client event attribute and handle it:
myTextBox.Attributes.Add("onchange",
"this.style.backgroundColor = (this.value != '')?'#fff':'yellow';");
Hope it helps!
Sample java Script
<script type="text/javascript" language="javascript">
function runScript(evt, ID) {
var ctl = document.getElementById(ID.id);
if (ctl.value == '') {
ctl.style.backgroundColor = '#FFFF00';
}
else
ctl.style.backgroundColor = '#FFFFFF';
return true;
}
</script>
Sample Repeater Control HTML
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table>
<tr>
<td>
textBox
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:TextBox ID="ed" runat="server" BackColor="Yellow" onkeyUp="return runScript(event, this)" autocomplete="off"></asp:TextBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Thank you guys for the help. This is the final code I used
.aspx.cs.
textBox.Attributes.Add("onkeypress","javascript:changebackgroundcolor()");
.aspx
<script type="text/javascript">
function changebackgroundcolor() {
var element;
for (var i = 0; i < document.forms[0].elements.length; i++) {
element = document.forms[0].elements[i];
switch (element.type) {
case 'textarea':
if (element.value.length > 0) {
element.style.borderwidth = "thin";
element.style.bordercolor = "White";
element.style.borderstyle = "solid";
}
break;
}
}
}
</script>

Categories