I have created the following chart using google organisation chart but I have some problems. When I open the page or when I refresh the page it shows up the full chart like in picture below. But I want only the items that are in red square to be shown how can I do this.
I do not want to get a few items from the list but when I open the page it shows the whole chart with its all list item and instead when it opens I want to display only 5 items and let user to expand others do you understand me?
This is the picture of chart how it looks like and how I want it to be!
And here is my full c# code:
namespace OrganizationChartUsingGoogleAPI.OrganizationChart
{
public static class ConvertTo
{
/// <summary>
/// Convert the object type in the given type and handle the DBNULL.
/// </summary>
/// <typeparam name="T">Type to convert</typeparam>
/// <param name="value">value</param>
/// <returns>converted value and if DBNULL then return the type's default value i.e. string = string.Empty, Int16=0 </returns>
public static T CastIn<T>(this object value) where T : IConvertible
{
if (value == DBNull.Value)
if (typeof(T) == typeof(string))
{
return (T)Convert.ChangeType(string.Empty, typeof(T));
}
else
{
return default(T);
}
if (typeof(T) == typeof(bool))
return (T)Convert.ChangeType(Convert.ToInt32(value), typeof(T));
return (T)Convert.ChangeType(value, typeof(T));
}
}
public partial class OrganizationChartUserControl : UserControl
{
//Get the List name to fetch the data from
string listName = "OrgChart_Demo";
int iRowCounter = 0;
string sAllNewRows = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
//Fetch the data (recursively) from the list
GetNode(string.Empty);
//Generate the Client Script and Register
GenerateClientScript(sAllNewRows);
}
private void GenerateClientScript(string sAllNewRows)
{
string csName1 = "OrgChartScript";
Type csType = this.GetType();
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(csType, csName1))
{
StringBuilder cstext = new StringBuilder();
cstext.Append("<script type='text/javascript' src='https://www.google.com/jsapi'></script>");
cstext.Append("<script type='text/javascript'>");
cstext.Append("google.load('visualization', '1', { packages: ['orgchart'] });");
cstext.Append("google.setOnLoadCallback(drawChart);");
cstext.Append("function drawChart() {");
cstext.Append("var data = new google.visualization.DataTable();");
cstext.Append("data.addColumn('string', 'Name');");
cstext.Append("data.addColumn('string', 'Manager');");
cstext.Append("data.addColumn('string', 'ToolTip');");
cstext.Append("var rowArr = new Array();");
cstext.Append(sAllNewRows);
cstext.Append("data.addRows(rowArr);");
cstext.Append("var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));");
cstext.Append("chart.draw(data, { allowHtml: true, allowCollapse: true });");
cstext.Append("}");
cstext.Append("</script>");
cs.RegisterClientScriptBlock(csType, csName1, cstext.ToString(), false);
}
}
private void GetNode(string reportsTo)
{
SPListItemCollection itemCol = GetListItems(listName, reportsTo);
foreach (SPListItem item in itemCol)
{
//create a new row
sAllNewRows += createNewRow(item);
//Recursion
GetNode(item["Name"].ToString());
}
}
private string createNewRow(SPListItem listItem)
{
//Converting list items to strings.
string sName = ConvertTo.CastIn<string>(listItem["Name"]);
string sTitle = ConvertTo.CastIn<string>(listItem["Title"]);
string sMoreInfo = ConvertTo.CastIn<string>(listItem["MoreInfo"]);
string sReportsTo = ConvertTo.CastIn<string>(listItem["ReportsTo"]);
//Checking if image field ref is empty or null (if it does't provide any img source link!)
ImageFieldValue pageImage = listItem["Pageimage"] as ImageFieldValue;
string sPicture = string.IsNullOrEmpty(pageImage.ImageUrl) ? "#" : pageImage.ImageUrl;
StringBuilder sText = new StringBuilder();
sText.Append("var NewRow = new Array();");
//this row shows the image and everything else what chart needs
sText.Append(String.Format("NewRow.push({{ v: '{0}', f: '<img src =\"{1}\" style=\"width:57px; height:57px; float:left;\" />{2}<div style=\"color:white; font-style:Arial\">{3}</div>' }});", sName, sPicture, sName, sTitle));
sText.Append(String.Format("NewRow.push('{0}');", sReportsTo));
sText.Append(String.Format("NewRow.push('{0}');", sMoreInfo));
//sText.Append(String.Format("NewRow.push('{0}');", sPicture));
sText.Append(String.Format("rowArr[{0}] = NewRow;", iRowCounter));
//Pageimage
iRowCounter++;
return sText.ToString();
}
private SPListItemCollection GetListItems(string destList, string reportsTo)
{
SPListItemCollection ResultListItems = null;
using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPList list = oWeb.Lists.TryGetList(destList);
if (null == list)
return ResultListItems;
string selected = DropDownList2.SelectedValue;
// Label1.Text = selected;
//Check if the item already exist.
StringBuilder sCAMLQuery = new StringBuilder(string.Empty);
sCAMLQuery.Append("<Where>");
sCAMLQuery.Append("<And>");
if (reportsTo != string.Empty)
{
sCAMLQuery.Append("<Eq>");
sCAMLQuery.Append("<FieldRef Name='ReportsTo' />");
//sCAMLQuery.Append("<Value Type='Lookup'>" + reportsTo + "</Value>");
sCAMLQuery.Append("<Value Type='Text'>" + reportsTo + "</Value>");
sCAMLQuery.Append("</Eq>");
}
else
{
sCAMLQuery.Append("<IsNull>");
sCAMLQuery.Append("<FieldRef Name='ReportsTo' />");
sCAMLQuery.Append("</IsNull>");
}
sCAMLQuery.Append("<Eq>");
sCAMLQuery.Append("<FieldRef Name='Kompania' />");
//sCAMLQuery.Append("<Value Type='Lookup'>" + reportsTo + "</Value>");
sCAMLQuery.Append("<Value Type='Text'>" + selected + "</Value>");
sCAMLQuery.Append("</Eq>");
sCAMLQuery.Append("</And>");
sCAMLQuery.Append("</Where>");
SPQuery QueryResult = new SPQuery();
QueryResult.Query = sCAMLQuery.ToString();
ResultListItems = list.GetItems(QueryResult);
}
}
return ResultListItems;
}
}
}
Thanks all of you
I see you have a GetNode(string reportsTo).
could you pass the level you're in and return if the level gets higher than you want?
private void GetNode(string reportsTo, int level)
{
// maybe have some config or value you can set for the max level you want.
if (level >= 2) return;
SPListItemCollection itemCol = GetListItems(listName, reportsTo);
foreach (SPListItem item in itemCol)
{
//create a new row
sAllNewRows += createNewRow(item);
//Recursion
GetNode(item["Name"].ToString(). ++level);
}
}
Related
Mainly the application I am buiding should be able to insert the title, description time and date the title is created. This is the database table I have created
for inserting title, content, date and time for an journal application.
While I was executing " the error as journal table column does not have a date " error occurred.
public class JournalDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "JOURNal_db";
private static final String DATABASE_TABLE = "Journal_table";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME= "time";
public JournalDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create = " CREATE TABLE "+DATABASE_TABLE+"("+KEY_ID+"INTEGER PRIMARY KEY,"+
KEY_TITLE+"TEXT,"+
KEY_CONTENT+"TEXT,"+
KEY_DATE+"TEXT,"+
KEY_TIME+"TEXT" +")";
Log.d("dbHarry","Query being run is : "+ create);
db.execSQL(create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
if (i >= i1)
return;
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
public void addJournal(Journal journal){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_TITLE,journal.getTitle());
contentValues.put(KEY_CONTENT,journal.getContent());
contentValues.put(KEY_DATE,journal.getDate());
contentValues.put(KEY_TIME,journal.getTime());
db.insert(DATABASE_TABLE,null,contentValues);
db.close();
}
public Journal getJournal(long id){
// select * from the databaseTable where id = 1
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,new String[]{KEY_ID,KEY_TITLE,KEY_CONTENT,KEY_DATE,KEY_TIME},KEY_ID+"?",
new String[]{String.valueOf(id)},null,null,null);
if(null != cursor) {
cursor.moveToFirst();
}
return new Journal(cursor.getLong(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
}
public List<Journal> getJournals(){
SQLiteDatabase db = this.getReadableDatabase();
List<Journal> allJournals = new ArrayList<>();
// SELECT * FROM DATABASE NAME
String query = " SELECT * FROM " + DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()) {
do {
Journal journal = new Journal();
journal.setID(cursor.getLong(0));
journal.setTitle(cursor.getString(1));
journal.setContent(cursor.getString(2));
journal.setDate(cursor.getString(3));
journal.setTime(cursor.getString(4));
allJournals.add(journal);
} while (cursor.moveToNext());
}
return allJournals;
}
}
Blockquote
Blockquote
This is the screenshot of error
According to your log, there is no column named "date" in your table, check it please.
i am use asp.net core code for popup and append html and js file in main view but i get error like $ not found if anyone know how to solve please help
My ActionFilter Code:-
private readonly IStoreContext _storeContext;
private readonly ISettingService _settingService;
private readonly ILogger _logger;
private readonly ILocalizationService _localizationService;
private readonly IWorkContext _workContext;
private readonly ITopicService _topicService;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
#endregion
#region const
public PopupEngageFilterAttribute()
{
this._storeContext = EngineContext.Current.Resolve<IStoreContext>();
this._settingService = EngineContext.Current.Resolve<ISettingService>();
this._logger = EngineContext.Current.Resolve<ILogger>();
this._localizationService = EngineContext.Current.Resolve<ILocalizationService>();
this._workContext = EngineContext.Current.Resolve<IWorkContext>();
this._topicService = EngineContext.Current.Resolve<ITopicService>();
this._newsLetterSubscriptionService = EngineContext.Current.Resolve<INewsLetterSubscriptionService>();
}
#endregion
#region methods
public void PopupEngageOnResultExecuted(ActionExecutedContext filterContext)
{
var storeId = _storeContext.CurrentStore.Id;
LicenseImplementer licenseImplementer = new LicenseImplementer();
// load plugin settings
var _setting = _settingService.LoadSetting<PopupEngageSetting>(storeId);
var allStoreSettings = _settingService.LoadSetting<PopupEngageSetting>(0);
//check plugin is enabled or not
if (_setting.PopupEngageEnabled)
{
// check license
//if (!licenseImplementer.IsLicenseActive(allStoreSettings.LicenseKey, allStoreSettings.OtherLicenseSettings))
// return;
StringBuilder sb = new StringBuilder();
string bioepEngageScript = string.Empty;
string popupEngageView = string.Empty;
string popupEngageScript = string.Empty;
string newsLetterScript = string.Empty;
// get current customer
var customer = _workContext.CurrentCustomer;
// check customer cart
string customerCart = Convert.ToString(customer.HasShoppingCartItems);
// set cookie for customer cart
filterContext.HttpContext.Response.Cookies.Append("CustomerCart", customerCart, new CookieOptions() { Path = "/", HttpOnly = false, Secure = false });
if(customerCart == "True")
{
// get bioep script file
Stream bioepScriptFile = Assembly.GetExecutingAssembly().GetManifestResourceStream("Nop.Plugin.XcellenceIt.PopupEngage.Script.bioep.min.js");
if (bioepScriptFile != null)
using (StreamReader reader = new StreamReader(bioepScriptFile))
{
bioepEngageScript = reader.ReadToEnd();
}
// get PopupEngage script
string path = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Script"), "PopupEngage.js");
if (File.Exists(path))
{
popupEngageScript = File.ReadAllText(path);
}
// check current customers role
var customerRole = customer.CustomerRoles.Where(x => x.Name == "Guests").FirstOrDefault();
if (customerRole != null)
{
// get Popup View file
string popupEngageViewFile = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Views"), "PopupEngage"), "PopupEngageNewsLetter.html");
if (File.Exists(popupEngageViewFile))
{
popupEngageView = File.ReadAllText(popupEngageViewFile);
}
// get NewsLetter Script file
Stream newsLetterScriptFile = Assembly.GetExecutingAssembly().GetManifestResourceStream("Nop.Plugin.XcellenceIt.PopupEngage.Script.NewsLetter.js");
if (newsLetterScriptFile != null)
using (StreamReader reader = new StreamReader(newsLetterScriptFile))
{
newsLetterScript = reader.ReadToEnd();
}
}
else
{
// get Popup View file
string popupEngageViewFile = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Path.Combine(Environment.CurrentDirectory.ToString(), "Plugins"), "XcellenceIt.PopupEngage"), "Views"), "PopupEngage"), "PopupEngage.html");
if (File.Exists(popupEngageViewFile))
{
popupEngageView = File.ReadAllText(popupEngageViewFile);
}
}
var topicBody=string.Empty;
// get topic from settings
var topic = _setting.TopicName;
if (!string.IsNullOrEmpty(topic))
{
// get topic by system name
var topicRecord = _topicService.GetTopicBySystemName(topic);
if(topicRecord != null)
{
topicBody = topicRecord.Body;
}
}
// replace new line with slash and double coute with single coute
popupEngageView = popupEngageView.Replace(Environment.NewLine, String.Empty).Replace("\"", "'");
topicBody = topicBody.Replace(Environment.NewLine, String.Empty).Replace("\"", "'");
// append script
sb.Append("<script type=\"text/javascript\" src=\"/wwwroot/lib/jquery-1.10.2.min.js\">\n\t");
sb.Append(bioepEngageScript);
sb.Append(popupEngageScript);
sb.Append("$(\"" + popupEngageView + "\").insertAfter(\".newsletter\");");
sb.Append("$('.popupengage_popupmsg').html(\"" + topicBody + "\");");
sb.Append(newsLetterScript);
sb.Append("</script>\n");
var bytes = Encoding.ASCII.GetBytes(sb.ToString());
filterContext.HttpContext.Response.Body.WriteAsync(bytes,0, bytes.Length);
}
}
}
#endregion
file append in perfect way but it append script in top of the page before jquery. and that script append by string builder.Popup js example
if u are using jquery, make sure it is included before the script files that use jquery functionality;
For ex: if u have a js file named 'main.js' which has includes a line like $().forEach then your order of inclusion in the html file should be
<script>jquery.js </scrpt>
<script>main.js </scrpt>
I am working on custom validation in mvc. I am using requiredif attribute. It’s working on server side but not on client side.
RequiredIfAttribute.cs
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
protected RequiredAttribute _innerAttribute;
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public bool AllowEmptyStrings
{
get
{
return _innerAttribute.AllowEmptyStrings;
}
set
{
_innerAttribute.AllowEmptyStrings = value;
}
}
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
_innerAttribute = new RequiredAttribute();
DependentProperty = dependentProperty;
TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
// trim spaces of dependent value
if (dependentValue != null && dependentValue is string)
{
dependentValue = (dependentValue as string).Trim();
if (!AllowEmptyStrings && (dependentValue as string).Length == 0)
{
dependentValue = null;
}
}
// compare the value against the target value
if ((dependentValue == null && TargetValue == null) ||
(dependentValue != null && (TargetValue.Equals("*") || dependentValue.Equals(TargetValue))))
{
// match => means we should try validating this field
//if (!_innerAttribute.IsValid(value))
if(value==null)
// validation failed - return an error
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
//public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
//{
//}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object, and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
}
public virtual IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
//IEnumerable<ModelClientValidationRule> IClientValidatable.GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (TargetValue ?? "").ToString();
if (TargetValue is bool)
targetValue = targetValue.ToLower();
rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);
yield return rule;
}
}
requiredif.js
$(function () {
alert('hii');
$.validator.addMethod('requiredif', function (value, element, parameters) {
alert(value);
var id = '#' + parameters['dependentproperty'];
alert(id);
// get the target value (as a string,
// as that's what actual value will be)
var targetvalue = parameters['targetvalue'];
targetvalue = (targetvalue == null ? '' : targetvalue).toString();
// get the actual value of the target control
// note - this probably needs to cater for more
// control types, e.g. radios
var control = $(id);
var controltype = control.attr('type');
var actualvalue =
(controltype === 'checkbox' || controltype === 'radio') ?
control.attr('checked').toString() :
control.val();
// if the condition is true, reuse the existing
// required field validator functionality
if ($.trim(targetvalue) === $.trim(actualvalue) || ($.trim(targetvalue) === '*' && $.trim(actualvalue) !== ''))
return $.validator.methods.required.call(
this, value, element, parameters);
return true;
});
$.validator.unobtrusive.adapters.add(
'requiredif',
['dependentproperty', 'targetvalue'],
function (options) {
options.rules['requiredif'] = {
dependentproperty: options.params['dependentproperty'],
targetvalue: options.params['targetvalue']
};
options.messages['requiredif'] = options.message;
});
});
Model
[Required]
public bool IsFeederSelected { get; set; }
[RequiredIf("IsFeederSelected", true, ErrorMessage = "You must enter purchase date")]
[Display(Name = "Meter Name")]
public List<string> SelectedMeterName { get; set; }
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.
I have a view pager, each page have a textview, I have parsed html document (without javascript) in my textview, I have many anchor tags inside this document, I want to call JavaScript function in anchor tag click. For e.g.
<a class="pginternal" tag="{http://www.w3.org/1999/xhtml}a" onclick="GoToPageNumber(186)" style="color:Blue !important;cursor:pointer !important;text-decoration:underline !important">THE VAMPIRE'S SIXTH STORY — In Which Three Men Dispute about a Woman.</a>
There is "GoToPageNumber" event , how to change pager item position on click of this.
I have found solution. Set movement method to textview.
textview.setMovementMethod(LinkMovementMethodExt.getInstance());
public static class LinkMovementMethodExt extends LinkMovementMethod
{
private static LinkMovementMethod sInstance;
public static MovementMethod getInstance()
{
if (sInstance == null)
{
sInstance = new LinkMovementMethodExt();
}
return sInstance;
}
int off = 0;
#Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event)
{
int action = event.getAction();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN)
{
try {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int currentLine = layout.getLineForVertical(y);
int totalLine = layout.getLineCount();
off = layout.getOffsetForHorizontal(currentLine, x);
} catch (Exception e) {
e.printStackTrace();
}
try {
URLSpan[] urls = buffer.getSpans(off, off+1, URLSpan.class);
for(URLSpan span : urls)
{
String urlStr = span.getURL();
Log.v("URL SPAN", urlStr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
}
You can't run JavaScript in a TextView. You will have to instead do everything in java with click listeners. If you want only handle a click on only a link within a TextView, you will need to learn how to use a Spannable. You can get help on that here.
I'm trying to use some javascript on a page layout, and I'm encountering a strange issue where the ClientID of a Sharepoint.WebControls.TextField seems to change between OnLoad and the page being displayed.
In the OnLoad event, TextField3.ClientID resolves to "ctl00_PlaceHolderMain_TextField3", but if look to see why my js doesn't work, the page source reveals that the control id to be "ctl00_PlaceHolderMain_TextField3_ctl00_TextField".
Any ideas what's going on?
Here's the code I'm using:
public class PostingTemplate : Microsoft.SharePoint.Publishing.PublishingLayoutPage
{
protected DropDownList author;
protected TextField TextField3;
private List<string> _authorNames;
public List<string> AuthorName
{
get { return _authorNames; }
set { _authorNames = value; }
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
author.AutoPostBack = false;
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"fillInAuthorText", getQuery(), true);
author.Attributes.Add("onChange", "fillInAuthorText()");
if (!Page.IsPostBack)
{
_authorNames = new List<string>();
_authorNames = Utilities.GetAuthorList(SPContext.Current.Site);
author.DataSource = _authorNames;
author.DataBind();
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (author.Items.Count > 0)
{
author.SelectedIndex = 0;
TextField3.Text = ((ListItem)author.Items[author.SelectedIndex]).Text;
}
}
private string getQuery()
{
string query = #" function fillInAuthorText() {
var IndexValue = document.getElementById('";
query += author.ClientID;
query += #"').selectedIndex;
var SelectedVal = document.getElementById('";
query += author.ClientID;
query += #"').options[IndexValue].value;
document.getElementById('";
query += TextField3.ClientID;
query += #"').value = SelectedVal;
}";
return query;
}
}
You need to include the client ID of the parent control as well.
// Replace:
query += author.ClientID;
// With:
query += base.ClientID + "_" + author.ClientID;
(Note that I've only ever done this with a web part so there may be some tweaking you need to do for it to work in a page layout.)
Another option is to resolve this client side. See Eric Shupp's blog for most info.
With help form Alex Angas, Here is what I discovered:
The TexField renders out some literals that end up surrounding a textbox, and it's really the textbox that you're interested in. Here's the modified section of code:
private string getQuery()
{
string query = #" function fillInAuthorText() {
var IndexValue = document.getElementById('";
query += author.ClientID;
query += #"').selectedIndex;
var SelectedVal = document.getElementById('";
query += author.ClientID;
query += #"').options[IndexValue].value;
document.getElementById('";
query += getTextFieldID(TextField3);
query += #"').value = SelectedVal;
}";
return query;
}
private string getTextFieldID(Control txt)
{
foreach (Control c in txt.Controls)
{
if (c.HasControls())
{
foreach (Control con in c.Controls)
if (con is TextBox)
return con.ClientID;
}
}
return "";
}
Keep in mind, this is specific to my application, your mileage my vary.