GridView Header Text in asp.net using asp:BoundField - asp.net

I want to change the header text of the gridview using Design..
<asp:BoundField HeaderText="">
i created a variable in javascript and initialize variable defending on the condition and then i tried to call that variable over here as below:
<asp:BoundField HeaderText="Text Here" DataField="slno" >
here I use "text here" string stored in one variavble name . and i want to use that variable
My code :
<script type="text/javascript" language="javascript">
/// <summary>
/// TO ACCESS COOKIE VARIABLE
/// </summary>
var flag;
var ca = document.cookie.split('=');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ',') c = c.substring(1);
}
if (c != '' && c != null) {
flag = c;
}
else {
flag = 1;
}
//*********************************************
if (flag == 1) {
var name_lbl = "Hai";
}
else if (flag == 2) {
var name_lbl = "How are you?";
}
</script>
//------------------------------------------------
</asp:Content>
<form id="form1" runat="server">
</table>
<div style="overflow: auto; height: 99%;" id="divTable">
<table><tr><td>
<label for='field ID'> <b><input type="text" id="kilist_lbl" size="20" style="border: none; height:20px" readonly/></b> </label> <br />
</td></tr></table>
<asp:GridView ID="gvareadetails" runat="server"
CssClass="mGrid" AutoGenerateColumns="False">
<Columns>
<%-- here is the problem when assigning ID to headerText label --%>
<asp:BoundField HeaderText='sss' DataField="slno" >
<ItemStyle Width="5%" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
</form>
<script type="text/javascript" language="javascript">
document.getElementById('sss').value = name_lbl;
</script>
</asp:Content>
Any one have any suggestions how this could be achieved..

Instead of js, just try the C# code to get values from the grid view.
ex:
int name_lbl = gvareadetails.Columns[0][0];
Here Columns[0][0] gives you the first row first column value.

C# code to get values from the grid view:
string name_lbl;
protected void Page_Load(object sender, EventArgs e)
{
//---------------------------------------------
/// </summary>
/// /// <summary>
/// TO ACCESS COOKIE VARIABLE
/// </summary>
string b;
HttpCookie a = Request.Cookies["LangaugaeObj"];
if (a != null) b = a.Value; else b = "1";
if (b == "1")
{
name_lbl = "Hai";
}
else
{
name_lbl = "How are you";
}
//---------------------------------------------------
protected void Button1_Click(object sender, EventArgs e)
{
// here I set the variable name to the grid Header
gvareadetails.Columns[0].HeaderText = name_lbl;
Report report = new Report();
report.areaid = hidStatus.Value.ToString();
DataSet ds = report.getareawisedetails();
gvareadetails.DataSource = ds;
gvareadetails.DataBind();
ds.Dispose();
ds = null;
report = null;
}
Thank You for Shaji SS for his suggestion.. I hope this answer will help to someone who looking for- set the header text dynamically in asp.net using asp:BoundField.

Related

Failed to load viewstate - dynamic controls in ASP.NET

I have read many articles on viewstate but I can't get my head around it.
Basically I want to have two listboxes with add and remove buttons and a Proceed button.
When the Proceed button is pressed, the previous is hidden and a textbox is presented for each item in the first list box with 2 drop down boxes to describe it + a textbox for each item in the second list box (also for the user to add a description).
I then want a Finalise Button to save all this information to a database.
So far I have the following code:
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
CreateDynamicControls();
Page.MaintainScrollPositionOnPostBack = true;
Build2.Visible = false;
Build3.Visible = false;
Build4.Visible = false;
Finish.Visible = false;
}
void AddC_Click(Object sender, EventArgs e)
{
criteria.Items.Add(addnewc.Text.ToString());
addnewc.Text = null;
}
void RemoveCriterion_Click(Object sender, EventArgs e)
{
for (int i = 0; i < criteria.Items.Count; i++)
{
if (criteria.Items[i].Selected)
{
criteria.Items.Remove(criteria.Items[i]);
i--;
}
}
}
void AddAlternative_Click(Object sender, EventArgs e)
{
alternatives.Items.Add(addnewa.Text.ToString());
addnewa.Text = null;
}
void RemoveAlternative_Click(Object sender, EventArgs e)
{
for (int i = 0; i < alternatives.Items.Count; i++)
{
if (alternatives.Items[i].Selected)
{
alternatives.Items.Remove(alternatives.Items[i]);
i--;
}
}
}
void Continue_Click(Object sender, EventArgs e)
{
Build1.Visible = false;
Build2.Visible = true;
Build3.Visible = true;
CreateDynamicControls();
Finish.Visible = true;
}
void CreateDynamicControls()
{
Build2.Controls.Clear();
Build3.Controls.Clear();
Build2.Controls.Add(new LiteralControl("<h3>Please define each criterion.</h3><p>By describing it and indicating if it is 1/2 and a/b.</p>"));
for (int i = 0; i < criteria.Items.Count; i++)
{
Build2.Controls.Add(new LiteralControl("<strong>" + criteria.Items[i].Text + "</strong> Description:<br />"));
TextBox criteriondesc = new TextBox();
Build2.Controls.Add(criteriondesc);
criteriondesc.ID = "c" + i.ToString();
criteriondesc.Rows = 3;
criteriondesc.Width = 850;
criteriondesc.TextMode = TextBoxMode.MultiLine;
Build2.Controls.Add(new LiteralControl("<br />"));
Build2.Controls.Add(new LiteralControl("Desc1: "));
DropDownList aim = new DropDownList();
aim.ID = i.ToString();
aim.Width = 250;
aim.Items.Add(new ListItem("1"));
aim.Items.Add(new ListItem("2"));
Build2.Controls.Add(aim);
Build2.Controls.Add(new LiteralControl(" Desc2: "));
DropDownList source = new DropDownList();
source.ID = i.ToString();
source.Width = 250;
source.Items.Add(new ListItem("a"));
source.Items.Add(new ListItem("b"));
Build2.Controls.Add(source);
Build2.Controls.Add(new LiteralControl("<br /><br />"));
}
Build3.Controls.Add(new LiteralControl("<h3>Please define each alternative.</h3><p>Please describe each alternaitve in detail.</p>"));
for (int i = 0; i < alternatives.Items.Count; i++)
{
Build3.Controls.Add(new LiteralControl("<strong>" + alternatives.Items[i].Text + "</strong> Description:<br />"));
TextBox altdesc = new TextBox();
altdesc.ID = "a" + i.ToString();
altdesc.Rows = 3;
altdesc.Width = 850;
altdesc.TextMode = TextBoxMode.MultiLine;
Build3.Controls.Add(altdesc);
Build3.Controls.Add(new LiteralControl("<br />"));
}
Build3.Controls.Add(new LiteralControl("<br /><h3>Review dates.</h3><p>Please select a date for a meeting.</p>"));
OboutInc.Calendar2.Calendar selectdates = new OboutInc.Calendar2.Calendar();
Build3.Controls.Add(selectdates);
}
void Finish_Click(Object sender, EventArgs e)
{
Build4.Visible = true;
foreach (var control in Build2.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
foreach (var control in Build3.Controls)
{
if (control.GetType() == typeof(TextBox))
{
Build4.Controls.Add(new LiteralControl(((TextBox)control).Text + "<br>"));
}
}
}
</script>
<asp:Content runat="server" ID="MainContent" ContentPlaceHolderID="MainContent">
<asp:Panel ID="Build1" runat="server">
<h3>What is your aim?</h3>
<p>
<asp:TextBox ID="goal" runat="server" Width="850px"></asp:TextBox>
</p>
<h3>What are the criteria of your decision?</h3>
<p>
<asp:ListBox ID="criteria" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveCriterion" runat="server" Text="Remove" OnClick="RemoveCriterion_Click" />
<asp:TextBox ID="addnewc" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddC" runat="server" Text="Add" OnClick="AddC_Click" />
</p>
</p>
<h3>What are the alternatives of your decision?</h3>
<p>
<asp:ListBox ID="alternatives" runat="server" Rows="8" Width="850px"></asp:ListBox><br />
<asp:Button ID="RemoveAlternative" runat="server" Text="Remove" OnClick="RemoveAlternative_Click" />
<asp:TextBox ID="addnewa" runat="server" Width="650px"></asp:TextBox>
<asp:Button ID="AddAlternative" runat="server" Text="Add" OnClick="AddAlternative_Click" />
</p>
<p align="right"><asp:Button ID="continue" runat="server" Text="Continue" OnClick="Continue_Click" /></p>
</asp:Panel>
<asp:Panel ID="Build2" runat="server">
</asp:Panel>
<asp:Panel ID="Build3" runat="server">
</asp:Panel>
<asp:Panel ID="Build4" runat="server">
</asp:Panel>
<p align="right"><asp:Button ID="Finish" runat="server" Text="Finish" OnClick="Finish_Click" /></p>
</asp:Content>
As you can see, at the minute I am just trying to output the user's text from the dynamically created textbox fields.
However, I am getting the error
Failed to load viewstate. The control tree into which viewstate is
being loaded must match the control tree that was used to save
viewstate during the previous request. For example, when adding
controls dynamically, the controls added during a post-back must match
the type and position of the controls added during the initial
request.
at: Line 169: Build3.Controls.Add(altdesc);
Does anyone know how to fix this problem with the viewstate?
I am very new to ASP.NET, my background is mainly in WinForms.
Thank you for any help and advice!!
You are creating your controls too late. You should create them during the Init events of the page, and not Page Load. I suggest You read abit about page life cycle
I think the best way to do it, it would be :
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
CreateDynamicControls();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
CreateDynamicControls();<br/>
}
Small sample:
http://class10e.com/Microsoft/which-method-should-you-add-to-the-web-page
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

How to change the value of input hidden on server-side

I have a form with hidden fields:
<form id="Form1" runat="server" style="width: 100%; height: 100%; overflow: hidden" onsubmit="return false;">
<div>
<input type="hidden" runat="server" id="TrackColors" value=""/>
<input type="hidden" runat="server" id="Relogin" value=""/>
</div>
</form>
After Page_Load() on the server-side is called function:
protected void SomeFunction()
{
Dictionary<int, int> trackColors = new Dictionary<int, int>();
if (!String.IsNullOrEmpty(TrackColors.Value))
trackColors = ReadValues(TrackColors.Value);
//if value is null or empty it's assigned to a different
TrackColors.Attributes["value"] = FormValues(trackColors); //FormValues() return string
//change is visible
}
string FormValues(Dictionary<int, int> values)
{
string result = "";
if (values == null || values.Count == 0)
return result;
foreach (KeyValuePair<int, int> p in values)
result += p.Key + "##" + p.Value + "^^";
result = result.TrimEnd('^');
return result;
}
If I change the selected field of ComboBox, the function is called:
<dx:ASPxTextBox ID="ColorTrackCarID" Visible="false" Text='<%# Eval("CarId") %>' />
<dx:ASPxComboBox ID="ASPxComboBox1" runat="server" SelectedIndex='<%# Eval("TrackColor") %>'
ValueType="System.String" Width="30" ShowImageInEditBox="true"
ondatabinding="ASPxComboBox1_DataBinding">
<ClientSideEvents SelectedIndexChanged="function (s,e) {
if (window.TrackColorChanged != null)TrackColorChanged(s,e); }" />
</dx:ASPxComboBox>
function TrackColorChanged(s, e) {
var TrackColors = document.getElementById('TrackColors');
if (TrackColors == null || TrackColors.value == "")
return values;
//values is always emply
}
I understand the value of the form fields are not passed back to the client-side. The question is: How to pass these values ​​back?
And if I change the value on the server-side in Page_Load (), then the client can see everything, that is,
protected void Page_Load(object sender, EventArgs e)
{
TrackColors.Attributes["value"] = "bla-bla-bla";
//All changes are visible on the client-side
}
Thank you for your attention.
To make it even easier, replace your hidden fields with the control:
<asp:HiddenField id="X" runat="server" />
Which you can set the value on it directly:
X.Value = "XYZ";
This value can be passed from client to server, and vice versa, and works very easily. Not that you can't use a server-side input, but HiddenField handles a lot of that for you.
EDIT: Also, are you sure you're not overwriting the value? If you are doing this:
protected void Page_Load(object sender, EventArgs e)
{
TrackColors.Attributes["value"] = "bla-bla-bla";
//All changes are visible on the client-side
}
This will always change the value to "bla-bla-bla". You would want to wrap it in if (!Page.IsPostback) if you initialize it on page load.

ASP.NET: Prevent User Controls from disappearing

On my Webpage I try to add User Control elements dependant on checked boxes in a tree view. Therefore I create a table that contains the tree view and a panel in which these elements should be loaded. The structure is like this:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script language="javascript" type="text/javascript">
function doCheckBoxPostBack(e) {
var event = window.event ? window.event.srcElement : e.target;
if (event.tagName == "INPUT" && event.type == "checkbox")
__doPostBack("", "");
}
</script>
<form id="form1" runat="server">
<h1>Status</h1>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<table>
<tr>
<td colspan="2" align="left" style="font-size:large">
Auswahl der anzuzeigenden Areas
</td>
</tr>
<tr>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<td valign="top">
<asp:TreeView ID="tvAreaSelect" runat="server"
onclick="doCheckBoxPostBack(event)" ShowCheckBoxes="All"
ontreenodecheckchanged="tvAreaSelect_TreeNodeCheckChanged">
<DataBindings>
<asp:TreeNodeBinding DataMember="System.Data.DataRowView" TextField="Text" ValueField="ID" />
</DataBindings>
</asp:TreeView>
</td>
<td>
<div style="overflow:auto; height:740px;">
<asp:Panel ID="panelContent" runat="server">
</asp:Panel>
</div>
</td>
</ContentTemplate>
</asp:UpdatePanel>
</tr>
</table>
</div>
</form>
</asp:Content>
In the code behind I load or unload my User Controls whenever one of the checkboxes changes its Checked value. This works just like it should, but when I press any button in one of the controls all of them disappear. Do I have to keep them in the cache or are there any other things to attend?
Here is a part of my code. I hope it makes clear what I'm doing.
protected void Page_Load(object sender, EventArgs e)
{
if (AreaIds.currList == null)
AreaIds.currList = new List<int>();
if (!this.Page.IsPostBack)
{
DataSet dsAreaGroups = dbStat.getDataSetAreaGroups();
DataSet dsAreasNotInAreaGroups = dbStat.getDataSetAreasNotInAreaGroups();
DataSet dsAreasInGroups = dbStat.getDataSetAreaGroupsWithAreas();
DataSet dsTree = new DataSet();
dsTree.Tables.Add("Table");
dsTree.Tables[0].Columns.Add("ID", typeof(string));
dsTree.Tables[0].Columns.Add("ParentID", typeof(string));
dsTree.Tables[0].Columns.Add("Text", typeof(string));
DataTableReader dtr = dsAreaGroups.CreateDataReader();
while (dtr.Read())
{
DataRow row = dsTree.Tables[0].NewRow();
object[] vals = new object[dtr.FieldCount];
dtr.GetValues(vals);
int inAreaGroupID = (int)vals.ElementAt(0);
string stName = (string)vals.ElementAt(1);
row["ID"] = inAreaGroupID;
row["Text"] = stName;
dsTree.Tables[0].Rows.Add(row);
}
dtr = dsAreasInGroups.CreateDataReader();
while (dtr.Read())
{
DataRow row = dsTree.Tables[0].NewRow();
object[] vals = new object[dtr.FieldCount];
dtr.GetValues(vals);
int inAreaID = (int)vals.ElementAt(0);
int inAreaGroupID = (int)vals.ElementAt(1);
string stName = (string)vals.ElementAt(2);
string stCombo = inAreaGroupID + "-" + inAreaID;
row["ID"] = stCombo;
row["ParentID"] = inAreaGroupID;
row["Text"] = stName;
dsTree.Tables[0].Rows.Add(row);
}
dtr = dsAreasNotInAreaGroups.CreateDataReader();
while (dtr.Read())
{
DataRow row = dsTree.Tables[0].NewRow();
object[] vals = new object[dtr.FieldCount];
dtr.GetValues(vals);
int inAreaID = (int)vals.ElementAt(0);
string stName = (string)vals.ElementAt(1);
row["ID"] = "0-" + inAreaID;
row["Text"] = stName;
dsTree.Tables[0].Rows.Add(row);
}
tvAreaSelect.SetDataSourceFromDataSet(dsTree, "ID", "ParentID");
tvAreaSelect.DataBind();
}
}
public void includeAreas(List<int> areaId)
{
int[] array = areaId.ToArray();
for (int i = 0; i < array.Length; i++)
{
Control ctrl = LoadControl("StatusArea.ascx", areaId[i]);
this.panelContent.Controls.Add(ctrl);
}
}
/// <summary>
/// Bereitstellung eines UserControl aus einer ascx-Datei
/// </summary>
/// <param name="UserControlPath">Das UserControl ascx-Datei</param>
/// <param name="constructorParameters">Parameter im Konstruktor der ascx.cs-Datei</param>
/// <returns>UserControl mit den entsprechenden Parametern</returns>
private UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
{
List<Type> constParamTypes = new List<Type>();
foreach (object constParam in constructorParameters)
{
constParamTypes.Add(constParam.GetType());
}
UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;
// Find the relevant constructor
System.Reflection.ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());
//And then call the relevant constructor
if (constructor == null)
{
throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString());
}
else
{
constructor.Invoke(ctl, constructorParameters);
}
// Finally return the fully initialized UC
return ctl;
}
protected void tvAreaSelect_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
TreeNode selNode = (TreeNode)e.Node;
TreeNode parentNode = selNode.Parent;
if (selNode.Checked && selNode.ChildNodes.Count == 0)
{
string stTest = selNode.Value.Substring(selNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
if (!AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Add(inAreaID);
}
if (!selNode.Checked && selNode.ChildNodes.Count == 0)
{
string stTest = selNode.Value.Substring(selNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
if (AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Remove(inAreaID);
}
foreach (TreeNode childNode in selNode.ChildNodes)
{
if (selNode.Checked)
{
string stTest = childNode.Value.Substring(childNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
childNode.Checked = true;
if (!AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Add(inAreaID);
}
else
{
string stTest = childNode.Value.Substring(childNode.Value.IndexOf("-") + 1);
int inAreaID = Convert.ToInt32(stTest);
childNode.Checked = false;
if (AreaIds.currList.Contains(inAreaID))
AreaIds.currList.Remove(inAreaID);
}
}
includeAreas(AreaIds.currList);
}
Thanks in advance
I do believe your problem resides on the fact that unfortunately you need to reload your dynamic controls on each and every postback.
One solution is to keep a in-session list of 'loaded' controls, and recreate them at Page_Init.

Populate ASPxTextBox and ASPxListBox from Code Behind

im using the Devexpress ASPxGridView for a project but are having problems to populate a custom EditForm with data.
It looks as follows
<Templates>
<EditForm>
Company Name:
<dx:ASPxTextBox ID="CompanyName" runat="server" Value="<% #Bind('CompanyName') %>" />
Parent:
<dx:ASPxListBox ID="ParentGuid" runat="server" Value="<% #Bind('ParentGuid') %>" />
</EditForm>
</Templates>
Normally I'd write something like
protected void ASPxGridView1_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
{
var CompanyList = db.companies.OrderBy(x => x.CompanyName).ToList();
ASPxListBox ParentGuid = (ASPxListBox)ASPxGridView1.FindControl("ParentGuid");
ParentGuid.DataSource = CompanyList;
ParentGuid.DataBind();
ASPxTextBox CompanyName = (ASPxTextBox)ASPxGridView1.FindControl("CompanyName");
CompanyName.Text = "Some company name";
}
But that wont work. Any advice where to start? The documentation doesn't really cover custom forms that well :/
Thanks!
== UPDATE ==
Tried using the onhtmleditformcreated="ASPxGridView1_HtmlEditFormCreated" with the method
protected void ASPxGridView1_HtmlEditFormCreated(object sender, ASPxGridViewEditFormEventArgs e)
{
Control CompanyName = ASPxGridView1.FindEditFormTemplateControl("CompanyName");
if (CompanyName != null)
{
ASPxTextBox CompanyNameEdit = CompanyName as ASPxTextBox;
CompanyName.Text = "Some Co";
}
}
The fact that I use Value="<% #Bind('CompanyName') %>" messes stuff up a bit. If i remove the Bind the boxes gets populated but then I have no way of fetching the data in them. Any way around this?
You should use a slightly different approach:
Use the HtmlEditFormCreated event to set editors properties. To obtain editor instances, use the gridView's FindEditFormTemplateControl method.
The answer is...
To populate a ASPxComboBox called CompanyList
protected void ASPxGridView1_HtmlEditFormCreated(object sender, ASPxGridViewEditFormEventArgs e)
{
Control ParentGuidControl = ASPxGridView1.FindEditFormTemplateControl("ParentGuid");
if (ParentGuidControl != null)
{
ASPxComboBox ParentGuid = (ASPxComboBox)ParentGuidControl;
var CompanyList = db.companies.OrderBy(x => x.CompanyName);
ParentGuid.TextField = "CompanyName";
ParentGuid.ValueField = "CompanyGuid";
ParentGuid.DataSource = CompanyList;
ParentGuid.DataBind();
}
}
BUT!
If you have a custom form like i had
<Templates>
<EditForm>
Company Name:
<dx:ASPxTextBox ID="CompanyName" runat="server" Value="<% #Bind('CompanyName') %>" />
Parent:
<dx:ASPxComboBox ID="ParentGuid" runat="server" Value="<% #Bind('ParentGuid') %>" />
</EditForm>
</Templates>
you wont be able to populate it from code-behind, the #bind method is in the way and overwrite any other incoming value. However if you are not planning to populate them from code behind here is a neat trick to fetch the data...
protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
IDictionaryEnumerator enumerator = e.NewValues.GetEnumerator();
string CompanyName = string.Empty;
Guid ParentGuid = Guid.Empty;
enumerator.Reset();
while (enumerator.MoveNext())
if (enumerator.Key.ToString() == "CompanyName")
CompanyName = enumerator.Value.ToString();
else if (enumerator.Key.ToString() == "ParentGuid")
ParentGuid = new Guid(enumerator.Value.ToString());
// Do insert trick here
}
But if you want to fill some of the form values from code-behind ensure there are no #bind methods in the EditForm
<Templates>
<EditForm>
Company Name:
<dx:ASPxTextBox ID="CompanyName" runat="server" />
Parent:
<dx:ASPxComboBox ID="ParentGuid" runat="server" />
</EditForm>
</Templates>
Populate as described in the top of this post and fetch the values like this
protected void ASPxGridView1_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
string CompanyName = string.Empty;
Guid ParentGuid = Guid.Empty;
// This method is a bit more secure
Control CompanyNameControl = ASPxGridView1.FindEditFormTemplateControl("CompanyName");
if (CompanyNameControl != null)
{
ASPxTextBox CompanyNameTb = (ASPxTextBox)CompanyNameControl;
CompanyName = CompanyNameTb.Text.ToString();
}
// A bit less secure, but lesser code
ASPxComboBox ParentGuidControl = (ASPxComboBox)ASPxGridView1.FindEditFormTemplateControl("ParentGuid");
ParentGuid = new Guid(ParentGuidControl.SelectedItem.Value.ToString());
// Do insert...
}
Have fun

How do I bind an ASP.net ajax AccordionPane to an XMLDatasource?

I've got an angry boss that will beat me down if I waste another day on this :-P Many karma points to the ajax guru who can solve my dilemma.
But more detail: I want to have an AccordionPane that grabs a bunch of links from an XML source and populate itself from said source.
There might be a sexier way, but this works. Populate your data source however you wish. This was just for demo purposes. Ditto for PrettyTitle() Key is to remember there are two item types in the accordion.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Accordion Binding</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="AjaxScriptManager" runat="server">
</asp:ScriptManager>
<div>
<cc1:Accordion ID="AccordionControl" runat="server"
onitemdatabound="AccordionControl_ItemDataBound">
<Panes></Panes>
<HeaderTemplate>
<asp:Label ID="HeaderLabel" runat="server" />
</HeaderTemplate>
<ContentTemplate>
<asp:Literal ID="ContentLiteral" runat="server" />
<asp:HyperLink ID="ContentLink" runat="server" />
</ContentTemplate>
</cc1:Accordion><asp:xmldatasource runat="server" ID="RockNUGTwitter" ></asp:xmldatasource>
</div>
</form>
</body>
</html>
And codebehind is :
Using System;
using System.Web.UI.WebControls;
using System.Xml;
namespace Ajaxy
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Fill();
}
private void Fill()
{
PopulateDataSource();
AccordionControl.DataSource = RockNUGTwitter.GetXmlDocument().SelectNodes("//item");
AccordionControl.DataBind();
}
private void PopulateDataSource()
{
XmlDocument RockNugTwitterRSSDocument = new XmlDocument();
RockNugTwitterRSSDocument.Load("http://twitter.com/statuses/user_timeline/15912811.rss");
RockNUGTwitter.Data = RockNugTwitterRSSDocument.OuterXml;
}
protected void AccordionControl_ItemDataBound(object sender, AjaxControlToolkit.AccordionItemEventArgs e)
{
XmlNode ItemNode = (XmlNode)e.AccordionItem.DataItem;
if(e.AccordionItem.ItemType == AjaxControlToolkit.AccordionItemType.Content)
{
HyperLink ContentLink = (HyperLink)e.AccordionItem.FindControl("ContentLink");
ContentLink.NavigateUrl = ItemNode.SelectSingleNode("link").InnerText;
Literal ContentLiteral = (Literal)e.AccordionItem.FindControl("ContentLiteral");
ContentLiteral.Text = ItemNode.SelectSingleNode("title").InnerText;
ContentLink.Text = "Link";
}
else if(e.AccordionItem.ItemType == AjaxControlToolkit.AccordionItemType.Header)
{
Label HeaderLabel = (Label) e.AccordionItem.FindControl("HeaderLabel");
HeaderLabel.Text = PrettyTitle(ItemNode.SelectSingleNode("title").InnerText);
}
}
private string PrettyTitle(string FullItem)
{
string PrettyString = FullItem.Replace("RockNUG: ", "");
string[] Words = PrettyString.Split(' ');
const int MAX_WORDS_TOSHOW = 4;
int WordsToShow = MAX_WORDS_TOSHOW;
if(Words.Length < MAX_WORDS_TOSHOW)
{
WordsToShow = Words.Length;
}
PrettyString = String.Join(" ", Words, 0, WordsToShow);
if (Words.Length > WordsToShow)
{
PrettyString += "...";
}
return PrettyString;
}
}
}

Resources