Dynamically creating ASP.NET form controls - asp.net

I have a form which, based on the answers given in the prior page, can have about 10 different variations in the combination of fields (most are the same, but several change). I decided rather than making 10 separate pages, I would try to make it dynamic. Eventually this will pull the form setup from a database, but for now I'm just trying to get the dynamic part to work. The following code kinda works, but it's giving me a weird result.
private void AddTestControls()
{
var newbox = new TextBox();
newbox.ID = "FirstBox";
newbox.Text = "This is dynamic";
newbox.CssClass = "stepHeader";
DynamicDiv1.Controls.Add(newbox);
var newlit = new Literal();
newlit.ID = "FirstLit";
newlit.Text = ".<br/>.";
DynamicDiv1.Controls.Add(newlit);
newbox.ID = "SecondBox";
newbox.Text = "This is also dynamic";
newbox.CssClass = "step";
DynamicDiv1.Controls.Add(newbox);
}
I've stepped through it and all the properties are getting set correctly, but when the page finally renders, only the SecondBox control is visible. There is no trace of the FirstBox. If I change it so that SecondBox is its own object (newebox2 for example) then both are visible, but with how I was thinking that I would ultimately do the form from the database, this could complicate things. I don't understand why the textbox object has to be recreated in order to add it to the Div's collection of controls. Am I going about this all wrong, or just missing a step somewhere?

Your "SecondBox" are overwriting the "FirstBox" newbox since it's still holding a reference to it. Create a new TextBox for the second box:
var newbox = new TextBox();
newbox.ID = "FirstBox";
newbox.Text = "This is dynamic";
newbox.CssClass = "stepHeader";
DynamicDiv1.Controls.Add(newbox);
var newlit = new Literal();
newlit.ID = "FirstLit";
newlit.Text = ".<br/>.";
DynamicDiv1.Controls.Add(newlit);
// Create a new TextBox
var secondBox = new TextBox();
secondBox.ID = "SecondBox";
secondBox.Text = "This is also dynamic";
secondBox.CssClass = "step";
DynamicDiv1.Controls.Add(secondBox);
I'm not quite sure why this could complicate things, but what you could do is create a method for creating a textbox, if that's easier:
TextBox CreateTextBox(string id, string text, string cssClass)
{
var box = new TextBox();
box.ID = id;
box.Text = text;
box.CssClass = cssClass;
return box;
}
And then
var newBox = CreateTextBox("FirstBox", "This is dynamic", "stepHeader");
DynamicDiv1.Controls.Add(newBox);

What's how it suppose to work. newbox1 is a reference so after the first time it's added to DynamicDiv1, it's there and if you change its Text, then the Text will be changed. You may find this SO useful. This SO demostrates the same issue you are having.

Related

How to get the selected value from a dropdown in MVC to use inside the view

I have an MVC app with leaflet running in it, I am parsing xml data to get the paths to the leaflet tiles which I then display in a drop down via a ViewData["value"]. The problem is I can't seem to figure out how to get that selected value and pass it down to the leaflet js as a path and then display everything. I tried many different ways to get the selection data but I'm just hitting a wall again and again.
The below code is how I send it to the view. I display it via an #Html.DropDownList("layerType", ViewData["value"] as List)
string outputPath;
outputPath = ConfigurationManager.AppSettings.Get("outputPath");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(outputPath + #"\log.xml");
XmlNodeList layerType = xDoc.GetElementsByTagName("layerType");
XmlNodeList layerPath = xDoc.GetElementsByTagName("layerPath");
XDocument doc = XDocument.Load(outputPath + #"\log.xml");
var count = doc.Descendants("layers")
.Descendants("layerData")
.Count();
List<SelectListItem> li = new List<SelectListItem>();
foreach (int i in Enumerable.Range(0, count))
{
li.Add(new SelectListItem { Text = layerPath[i].InnerText, Value = i.ToString() });
}
ViewData["value"] = li;
return View(li);
How would I get the selected data and simply pass it down into the leaflet part inside the js tags.
Would I maybe pass it back into a controller and then back to the view?
#Html.DropDownList("layerType",
new SelectList((IEnumerable) ViewData["value"]), "Value", "Text")
In the Post method, you have to fill the viewdata again to avoid error if model returns invalid
Refer Below Link :
MVC Select List with Model at postback, how?
Working Code
https://dotnetfiddle.net/2lrb2S
Get Value on View
<script>
var conceptName = $('#nameofyourdropdowncontrol').find(":selected").text();
//code for passing value
</script>

Issue with relation when creating record

I have two tables that are related as follows:
PMLprojects ONE - MANY Inovice_stat
I have a script to create a record in the Invoice_stat table. It goes as follows:
var myProjectList = app.datasources.PMLprojects;
var myProjectListID = myProjectList.Id;
var myDatasource = app.datasources.Invoice_stat;
var myCreateDatasource = myDatasource.modes.create;
now = new Date();
var draft = myDatasource.modes.create.item;
draft.EmailStatus = "Yes";
draft.PaidStatus = "No";
draft.DateCreate = now;
myCreateDatasource.createItem(function(newRecord) {
var key = newRecord._key;
});
myDatasource.saveChanges();
All the fields are properly populates except the relation to PMLprojects. How can I related the record from Invoice_stat to PMLprojects? I'm getting the following message:
Error log :
com.google.apps.appmaker.client.datasource.AbstractModelDataSource
WARNING: Could not select element with key RecordKey{key=private$6,
model
key=1Y8Ijd68IZyWFllY3d_C9fhAOFtVgKCtH|Gu5LnmmFmZHfEbrL5Ug1fybNaVLSEPn6}.
No records bound.
Here is some proposed edited code for you to try. However, do remember that if your PMLprojects datasource is not loaded on the client, then this will still fail. I also highly recommend that you check out the official documentation here https://developers.google.com/appmaker/models/relations#modify_associations.
var myProjectList = app.datasources.PMLprojects.item; //change this line to point to an item in the datasource
//var myProjectListID = myProjectList.Id; This line is not necessary
var myDatasource = app.datasources.Invoice_stat;
var myCreateDatasource = myDatasource.modes.create;
now = new Date();
var draft = myCreateDatasource.item; //you already declared the create mode
draft.EmailStatus = "Yes";
draft.PaidStatus = "No";
draft.DateCreate = now;
draft.YourRelationToPMLprojects = myProjectList; //here is where you create your relation, replace YourRelationToPMLprojects with your actual relation name should show up in code autocomplete
myCreateDatasource.createItem(function(newRecord) {
var key = newRecord._key;
});
myDatasource.saveChanges();
Since you are probably using both tables with the Manual Save mode... then #MarkusMalessa's approach might return you an error. If that is so, you have to make sure that you create the relation after you create the item but before you save changes. For that, take into consideration the following example:
var project = app.datasources.PMLprojects.item; //project item
var ds = app.datasources.Invoice_stat;
var createDs = ds.modes.create;
var draft = createDs.item;
draft.EmailStatus = "Yes";
draft.PaidStatus = "No";
draft.DateCreate = new Date();
createDs.createItem(function(){
ds.item.PMLproject = project; //here is where you create your relation
ds.saveChanges();
});
Just remember, this will only work as long as the PMLprojects datasource has already been loaded, otherwise you will probably get an error.

Find ListBoxes in ASP .NET

i have created dynamic listboxes (4 to 10) in ASP.NET.
and my question is , How do i find the dynamically created listboxes using c#?
thanks
Sure... and i appreciate your help . below code i am using for creating dynamic LB
protected void btndyfilter_Click(object sender, EventArgs e)
{
int numberOfListBox = lbFilter.GetSelectedIndices().Length;
string lbname = lbFilter.SelectedValue;
for (int i = 0; i < numberOfListBox; i++)
{
ListBox listb = new ListBox();
ListItem lItem = new ListItem();
listb.SelectionMode = System.Web.UI.WebControls.ListSelectionMode.Multiple;
listb.Height = 150;
listb.Width = 200;
lItem.Value = i.ToString();
lItem.Text = lbname;
listb.Items.Add(lItem);
panFilter.Controls.Add(listb);
//once we created the LB dynamically i need to populate each LB with the corresponding values
connstr2 = System.Configuration.ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
conn2.ConnectionString = connstr2;
conn2.Open();
CubeCollection CubeList = conn2.Cubes;
string cb = ddlCubeList.SelectedItem.Text;
//need to remove the Hardcoded Code
foreach (Member dimem in CubeList[cb].Dimensions["Date"].Hierarchies["Calendar Date"].Levels["Date"].GetMembers())
{
ListItem Memlist = new ListItem();
Memlist.Text = dimem.UniqueName;
lbFilter.Items.Add(Memlist);
}
}
panFilter.Visible = true;
panCubeDef.Visible = true;
}
so this will create the LB i believe :)... and Inside the commented code i need to use to populate for each LB item ..perhaps it bit hardcoded which i need to remove. so i all dynamic LBs are populated then the selected items from all LBs will come into the where clause in my MDX query..hope i did not confuse you
There is 2 way either you can store dynamic control detail with dictionary or just find when you want to use it using some code like this
Control GetControlByName(string Name)
{
foreach(Control c in this.Controls)
if(c.Name == Name)
return c;
return null;
}
while generating ListBox dynamically, give ListBox ID as:
lstBoxNo1, lstBoxNo2. lstBoxNo3 etc. where 1,2,3(no) will be from count.
like
int count=1;
generate listbox control
listboxid=lastBoxNo+count;
count++
`by doing this, u have control over id's.
else use
http://stackoverflow.com/questions/3731007/using-findcontrol-to-find-control
using this link to understand findcontrol.
The points that you wont to find that dynamic controls are.
The moment you first render the page.
On every other post back.
In the case of 1, then you better keep a variable on your page that keep that creations.
In the case of 2, when you have post back, you need to store somehow the creations of your control in the page when you render it. One good place is to keep that information on the viewstate.
You can also on the post back, just to check if you have any post back valued from controls that you have named with a serial numbering starting from 1, eg You start looking if you have post back from ControlName_1, then ControlName_2, and when you not found any other value you end.

How to search content inside source tab of a rich text field in Tridion

I am currently using the following code to search within Tridion. It is fetching the Items (Components and Pages) based on the input.
Question: In rich text field we have Design,Source and Preview tabs. The below code is searching for content present in Design tab only. I need the Source tab content also
to be considered while performing search.
CoreServiceSession client = new CoreServiceSession();
SessionAwareCoreServiceClient csClient = client.GetClient();
var find = new SearchQueryData
{
Description = "Universe"
ItemTypes = new ItemType[] { ItemType.Page, ItemType.Component }
);
IdentifiableObjectData[] foundItems = csClient.GetSearchResults(find);
Did you try with FullTextQuery
CoreServiceSession client = new CoreServiceSession();
SessionAwareCoreServiceClient csClient = client.GetClient();
ReadOptions readoption = new ReadOptions();
var find = new SearchQueryData
{
Description = "Universe"
FullTextQuery= "Universe"
ItemTypes = new ItemType[] { ItemType.Component }
);
IdentifiableObjectData[] foundItems = csClient.GetSearchResults(find);
As FullTextQuery can impact on your CMS performance, you may want it to restrict to particular schema components field only.
BasedOnSchemaData basedSchemaNote = new BasedOnSchemaData();
basedSchemaNote.Schema = new LinkToSchemaData() { IdRef = "tcm:XX-xxxx-8" };
basedSchemaNote.Field = "FieldName";
basedSchemaNote.FieldValue = "*SeachText*";

adding url to the hyperlink field in gridview

I have a dynamic grid view. I add column in page load.
I use this code for add Hyperlinkfield :
string[] url = new string[1];
url[0] = field.InternalName;
HyperLinkField link = new HyperLinkField();
link.HeaderText = field.Title;
link.DataNavigateUrlFields = url;
link.DataNavigateUrlFormatString = "{0}";
link.DataTextField = field.InternalName;
link.SortExpression = field.InternalName;
grid.Columns.Add(link);
my problem is : for example my url is "http://Test1.docx, http://Test1.docx".
I want navigateurl set "http://Test1.docx" .
If I am understanding correctly what the issue is. The field.InternalName field contains "http://Test1.docx, http://Test1.docx" to which you are assigning to a string array and you are trying to attempt to only get the first value before the comma.
In that case, you will need to split the string:
string[] urlSplit = field.InternalName.Split(',');
link.DataNavigateUrlFields = urlSplit[0];

Resources