Saving data read from sql database - c#-4.0

I have four textboxes and a metrogrid, inside the textboxes data is read into them from sql database, but while saving the data in the textboxes one will save and others will vanish. Please i need help
this is the code for search button:
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection(#"server = .\sql2012; database = dbAcceptance; integrated security = true; "))
{
SqlCommand command = new SqlCommand($"select * from acceptance WHERE regno = {txtregno.Text}", connection);
connection.Open();
SqlDataReader read = command.ExecuteReader();
if (read.Read())
{
txtfullname.Text = (read["fullname"].ToString());
txtdepartment.Text = (read["Department"].ToString());
txtfaculty.Text = (read["faculty"].ToString());
txtmodeofstudy.Text = (read["modeofstudy"].ToString());
txtprogramme.Text = (read["programmeofstudy"].ToString());
}
else
MetroFramework.MetroMessageBox.Show(this, "Reg No Not Found...Please Try Again", "Message");
read.Close();
}
}
catch (Exception ex)
{
//MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is the code for add button:
private void btnAdd_Click(object sender, EventArgs e)
{
objState = EntityState.Added;
pContainer.Enabled = true;
registeredBindingSource.Add(new Registered());
registeredBindingSource.MoveLast();
txtregno.Focus();
}
This is the code for the save button:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
registeredBindingSource.EndEdit();
Registered obj = registeredBindingSource.Current as Registered;
if (obj != null)
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
if (db.State == ConnectionState.Closed)
db.Open();
if (objState == EntityState.Added)
{
DynamicParameters p = new DynamicParameters();
p.Add("#StudentID", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.AddDynamicParams(new {
FullName = txtfullname.Text,
RegNo = txtregno.Text,
CourseTitle = obj.CourseTitle,
CourseStatus = obj.CourseStatus,
CourseUnit = obj.CourseUnit,
Department = txtdepartment.Text,
CurrentSemester = obj.CurrentSemester,
CurrentSession = obj.CurrentSession,
ModeOfStudy = txtmodeofstudy.Text,
Level = obj.Level,
ProgrammeOfStudy = txtprogramme.Text,
Faculty = txtfaculty.Text, finalSemester = obj.finalSemester
});
db.Execute("sp_StudentRegisteredCourse_insert", p, commandType: CommandType.StoredProcedure);
obj.StudentID = p.Get<int>("#StudentID");
}
else
{
db.Execute("sp_StudentRegisteredCourse_update", new { StudentID = obj.StudentID,FullName = txtfullname.Text,RegNo = txtregno.Text, CourseTitle = obj.CourseTitle,CourseStatus = obj.CourseStatus, CourseUnit = obj.CourseUnit, Department = txtdepartment.Text, CurrentSemester = obj.CurrentSemester,CurrentSession = obj.CurrentSession, ModeOfStudy = txtmodeofstudy.Text, Level = obj.Level, ProgrammeOfStudy = txtprogramme.Text,Faculty = txtfaculty.Text, finalSemester = obj.finalSemester },commandType:CommandType.StoredProcedure);
}
gridContainer.Refresh();
pContainer.Enabled = false;
objState = EntityState.unchanged;
}
}
}
catch (Exception ex)
{
MetroFramework.MetroMessageBox.Show(this, ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Related

C# Threads wont work when i show form with form.ShowDialog

MyForm myForm = new MyForm();
myForm.ShowDialog();
In the MyFormClass
private void MyForm_Load(object sender, EventArgs e)
{
nameLabel.Text = user.username;
waitForServerMsgThread = new Thread(() => {
Thread.CurrentThread.IsBackground = true;
AddMessage("Start of this thread");
try
{
stream = client.GetStream();
while (true)
{
AddMessage(client.Available.ToString());
if (client.Available > 0)
{
byte[] byteToRead = new byte[client.Available];
stream.Read(byteToRead, 0, byteToRead.Length);
MessageToClient message = (MessageToClient)Commands.FromBytes(byteToRead);
if (message.messageType == MessageToClient.MessageType.IncoimgMessage)
{
MessageFromPerson msg = (MessageFromPerson)message.Message;
AddMessage(msg.name + " says: " + msg.msg);
}
}
}
}
catch (Exception ex)
{
AddMessage("Could not load data from server error " + ex.ToString());
}
});
waitForServerMsgThread.Start();
FormClosing += (s, args) => waitForServerMsgThread.Abort();
}
And it wont even execute the thread no matter if put Thread.Start in _Load or When button is pressed.And no i cant load form with myForm.Show(); because it wont show it will close after i call it(ShowDialog() is called from Thread)

Sharepoint2013 webpart can't load custom dll from GAC

I'm trying to use a third party dll called ASPTokenInputLib in my sharepoint2013 webpart .
It was working for a while when I loaded it in the bin directory but when I tried to move it to the GAC it won't work and it's stopped working if I load it in the bin now as well.
The error I get is object reference not set to an instance of an object. The sharepoint logs shows
System.NullReferenceException: Object reference not set to an instance of an object. at ASPTokenInputLib.ASPTokenInput.OnLoad(EventArgs e)
My package manifest file includes
<Assemblies>
<Assembly Location="ASPTokenInputLib.dll" DeploymentTarget="GlobalAssemblyCache" />
<Assembly Location="BidSearchWebPart.dll" DeploymentTarget="GlobalAssemblyCache">
<SafeControls>
<SafeControl Assembly="BidSearchWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=59049686a9425568" Namespace="BidSearchWebPart.VisualWebPart1" TypeName="*" />
</SafeControls>
</Assembly>
If I remove any ASPTokenInput controls in the webpart the webpart loads correctly so I don't think there's a problem finding the control in the gac (I've used process monitor and it is looking in the correct place in the GAC to find the control). For some reason though it can't load the dll.
Any help would be much appreciated. Thanks!
My ascx.cs files is
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Web.Script.Serialization;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using ASPTokenInputLib;
namespace BidSearchWebPart.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public partial class BidSearchWebPart : WebPart
{
private enum Columns
{
BidRef, BidName, Client, Area, TeamLead
}
private string TeamLeadsData, ExecLeadsData, StagesData, SectorsData, ServicesData, GradesData, CostCentresData, ClientsData, AreasData;
public BidSearchWebPart()
{
TeamLeadsData = RunSP("uspSelectTeamLeads", "TeamLead", "Name", ConnectionString());
ExecLeadsData = RunSP("uspSelectExecTechLeads", "ExecutiveTechnicalLead", "Name", ConnectionString());
StagesData = RunSP("uspSelectStages", "StageID", "StageDescSearch", ConnectionString());
SectorsData = RunSP("spSelectMarketSectors", "SectorID", "MktSector", CCDConnectionString());
ServicesData = RunSP("spSelectAllServices", "ServiceID", "Service", CCDConnectionString());
GradesData = RunSP("uspSelectGrades", "GradeID", "GradeDesc", ConnectionString());
CostCentresData = RunSP("uspSelectCostCentres", "CostCentre", "Name", ConnectionString());
ClientsData = RunSP("spSelectAllClients", "CompanyRef", "CoName", CCDConnectionString());
AreasData = RunSP("uspSelectAreas", "AreaID", "AreaName", ConnectionString());
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
List<string> ddValues = new List<string>();
if (!Page.IsPostBack)
{
ddValues.Add("Greater than");
ddValues.Add("Less than");
ddCC.DataSource = ddValues;
ddFV.DataSource = ddValues;
ddCC.DataBind();
ddFV.DataBind();
}
btnSearch.Click += btnSearch_Click;
gvSearchResults.RowDataBound += gvSearchResults_RowDataBound;
tiTeamLead.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiTeamLead.DataSet = TeamLeadsData;
tiExecTechLead.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiExecTechLead.DataSet = ExecLeadsData;
tiStage.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiStage.DataSet = StagesData;
tiSector.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiSector.DataSet = SectorsData;
tiService.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiService.DataSet = ServicesData;
tiGrade.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiGrade.DataSet = GradesData;
tiCostCentre.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiCostCentre.DataSet = CostCentresData;
tiClient.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiClient.DataSet = ClientsData;
tiArea.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiArea.DataSet = AreasData;
}
void btnSearch_Click(object sender, EventArgs e)
{
//if (string.IsNullOrEmpty(txtProjectNo.Text) && string.IsNullOrEmpty(txtProjectName.Text) && string.IsNullOrEmpty(txtClient.Text) && string.IsNullOrEmpty(txtKeyword.Text)) // Do nothing if search text boxes are blank
//{
// return;
//} else {
gvSearchResults.PageIndex = 0;
DoSearch();
//}
}
protected void gvSearchResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSearchResults.PagerTemplate = null;
gvSearchResults.PageIndex = e.NewPageIndex;
DoSearch();
}
public void DoSearch()
{
DataTable dt = new DataTable();
string where = GetWhereClause();
if (!string.IsNullOrEmpty(where))
{
dt = FillTable("spSelectBidSearchResults", where);
}
gvSearchResults.DataSource = dt;
gvSearchResults.PageSize = 10;
gvSearchResults.PagerTemplate = null;
gvSearchResults.DataBind();
}
private DataTable FillTable(string storedProc, string where)
{
SqlConnection conn = new SqlConnection(ConnectionString());
conn.Open();
SqlCommand cmdProject = new SqlCommand(storedProc, conn);
cmdProject.CommandType = CommandType.StoredProcedure;
cmdProject.Parameters.AddWithValue("#whereclause", where);
SqlDataAdapter da = new SqlDataAdapter(cmdProject);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
conn.Close();
return dt;
}
private string Symbol(string ddText)
{
if (ddText.Equals("Greater than"))
{
return ">";
}
else
{
return "<";
}
}
private string GetWhereClause()
{
string where = "";
where = GetWhereForCol(txtBidName.Text, "", "BidName", "like", where);
where = GetWhereForCol(txtDescription.Text, "", "Description", "like", where);
where = GetWhereForCol(GetTokens(tiTeamLead), "", "TeamLead", "token", where);
where = GetWhereForCol(GetTokens(tiExecTechLead), "", "ExecutiveTechnicalLead", "token", where);
where = GetWhereForCol(txtConstructionCost.Text, ddCC.Text, "ConstructionCost", "numeric", where);
where = GetWhereForCol(txtFeeValue.Text, ddFV.Text, "FeeValue", "numeric", where);
where = GetWhereForCol(GetTokens(tiStage), "", "Stage", "token", where);
where = GetWhereForCol(GetTokens(tiSector), "", "PrimarySector", "token", where, "SecondarySector");
where = GetWhereForCol(GetTokens(tiService), "", "PrimaryService", "token", where);
where = GetWhereForCol(GetTokens(tiGrade), "", "Grade", "token", where);
where = GetWhereForCol(GetTokens(tiCostCentre), "", "PrimaryCostCentre", "token", where);
where = GetWhereForCol(GetTokens(tiClient), "", "ClientRef", "token", where);
where = GetWhereForCol(GetTokens(tiArea), "", "Area", "token", where);
return where;
}
private string GetWhereForCol(string text, string ddText, string colName, string colType, string where, string otherCol = "")
{
if (!string.IsNullOrEmpty(text))
{
if (colType.Equals("like"))
{
where = AddToWhere(where, colName + " LIKE '%" + text + "%'");
}
else if (colType.Equals("numeric"))
{
string symbl = Symbol(ddText);
where = AddToWhere(where, colName + " " + symbl + " " + text);
}
else if (colType.Equals("token"))
{
if (!string.IsNullOrEmpty(otherCol))
{
where = AddToWhere(where, "(" + colName + " in (" + text + ")");
where += " OR " + otherCol + " in (" + text + "))";
}
else
{
where = AddToWhere(where, colName + " in (" + text + ")");
}
}
}
return where;
}
private string AddToWhere(string where, string clause)
{
if (!string.IsNullOrEmpty(clause))
{
if (string.IsNullOrEmpty(where))
{
where = clause;
}
else
{
where += " AND " + clause;
}
}
return where;
}
private string GetTokens(ASPTokenInput ti)
{
StringBuilder strTokens = new StringBuilder();
List<ASPTokenInput.Item> items = ti.SelectedItems;
foreach (ASPTokenInput.Item item in items)
{
if (strTokens.Length > 0)
{
strTokens.Append(", ");
}
strTokens.AppendFormat("'{0}'", item.id);
}
return strTokens.ToString();
}
public string GetSPSingleValue(string spName, string spParamName, string spParamVal, string connectionStr)
{
try
{
SqlConnection conn = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(spName, conn);
cmd.Parameters.AddWithValue(spParamName, spParamVal);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
string result = cmd.ExecuteScalar().ToString();
conn.Close();
return result;
}
catch
{
return "";
}
}
void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l;
DataRowView rowView = (DataRowView)e.Row.DataItem;
string bidRef = rowView["BidRef"].ToString();
string teamLeadID = rowView["TeamLead"].ToString();
string teamLeadName = GetSingleRecord("uspSelectTeamLeadByID", ConnectionString(), "#TeamLead", teamLeadID);
l = (Label)e.Row.Cells[(int)Columns.TeamLead].FindControl("lblTeamLead");
l.Text = teamLeadName;
if (siteCollectionExists(bidRef))
{
l = (Label)e.Row.Cells[(int)Columns.BidRef].FindControl("lblBidRef");
HyperLink hl = new HyperLink();
hl.NavigateUrl = "http://bidstore.gleeds.net/bids/" + bidRef;
hl.Text = bidRef;
e.Row.Cells[(int)Columns.BidRef].Controls.Add(hl);
l.Text = "";
}
}
}
//Check if site collection exists at given web application
private static bool siteCollectionExists(string bidNr)
{
bool returnVal = false;
var r = SPContext.Current.Site.WebApplication.Sites.Where(site => site.Url.Contains(bidNr));
foreach (SPSite s in r)
{
returnVal = true;
}
return returnVal;
}
public string TeamLeads()
{
return TeamLeadsData;
}
public string ExecutiveTechnicalLeads()
{
return ExecLeadsData;
}
public string Stages()
{
return StagesData;
}
public string Sectors()
{
return SectorsData;
}
public string Services()
{
return ServicesData;
}
public string Grades()
{
return GradesData;
}
public string CostCentres()
{
return CostCentresData;
}
public string Clients()
{
return ClientsData;
}
public string Areas()
{
return AreasData;
}
public string GetSingleRecord(string spName, string connectionStr, string param, string value)
{
SqlConnection conn = new SqlConnection();
SqlCommand command = new SqlCommand(spName, conn);
conn = new SqlConnection(connectionStr);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue(param, value);
command.Connection = conn;
conn.Open();
string result = command.ExecuteScalar().ToString();
conn.Close();
return result;
}
public string RunSP(string spName, string idCol, string nameCol, string connectionStr)
{
ArrayList data = new ArrayList();
SqlConnection conn = new SqlConnection();
SqlCommand command = new SqlCommand(spName, conn);
conn = new SqlConnection(connectionStr);
command.CommandType = CommandType.StoredProcedure;
command.Connection = conn;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
data.Add(new TokenInputRow(dr[idCol].ToString(), dr[nameCol].ToString()));
}
conn.Close();
return Serialize(data);
}
private static string Serialize(object obj)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(obj);
}
private string ConnectionString()
{
return "Data Source=10.2.40.17;Initial Catalog=BidOpening;Persist Security Info=True;User ID=GTL_BidOpening_User;Password=G#rd3n12";
}
private string CCDConnectionString()
{
return "Data Source=10.2.40.17;Initial Catalog=CCDLive;Persist Security Info=True;User ID=GTL_CCDLive_User;Password=G#rd3n";
}
}
public class TokenInputRow
{
public string id;
public string name;
public TokenInputRow(string _id, string _name)
{
id = _id;
name = _name;
}
}
}
I am able to step through the page load, but I can't step into the ASPTokenInput dll. The code fails after the page load has finished.
The ti controls are included in my .ascx file as so %# Register TagPrefix="ati" Assembly="ASPTokenInputLib" Namespace="ASPTokenInputLib" %> ati:ASPTokenInput ID="tiTeamLead" runat="server" HintText="Start typing TeamLead..." />

Some trouble with ComboBox in Ext.net

I have a Page which a FormPanel(there's a ComboBox in it) and a TreePanel(has a default root node) in it and open ViewState.
I set a value to ComboBox in GET.
When i GET the page the TreePanel's Store send a POST request(store read) before FormPane rendered in client,in this POST request the fromdata has no info about FormPane.
in the POST request recover the ComboBox.Value from ViewState,but in ComboBoxBase.LoadPostData() Ext.Net get value from formdata and cover ComboBox.Value without precondition
it's ComboBoxBase.LoadPostData() code
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
if (!this.EmptyText.Equals(text) && text.IsNotEmpty())
{
List<ListItem> items = null;
if (this.SimpleSubmit)
{
var array = state.Split(new char[] { ',' });
items = new List<ListItem>(array.Length);
foreach (var item in array)
{
items.Add(new ListItem(item));
}
}
else if(state.IsNotEmpty())
{
items = ComboBoxBase.ParseSelectedItems(state);
}
bool fireEvent = false;
if (items == null)
{
items = new List<ListItem>
{
new ListItem(text)
};
/*fireEvent = this.SelectedItems.Count > 0;
this.SelectedItems.Clear();
return fireEvent;
*/
}
foreach (var item in items)
{
if (!this.SelectedItems.Contains(item))
{
fireEvent = true;
break;
}
}
this.SelectedItems.Clear();
this.SelectedItems.AddRange(items);
return fireEvent;
}
else
{
if (this.EmptyText.Equals(text) && this.SelectedItems.Count > 0)
{
this.SelectedItems.Clear();
return true;
}
}
return false;
}
Look at Line 5 to 11,why not change like this
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.Value = text;
this.ResumeScripting();
Sample for this question
page file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<ext:ResourceManager ID="ResourceManager1" runat="server" DisableViewState="false"
AjaxViewStateMode="Enabled" ViewStateMode="Enabled"/>
<form id="form1" runat="server">
<ext:Viewport runat="server" ID="VP">
</ext:Viewport>
</form>
</body>
</html>
cs file
public partial class WebFormTest : System.Web.UI.Page
{
protected override void OnInitComplete(EventArgs e)
{
FP = new FormPanel();
FP.ID = "FP";
FP.Title = "FP";
FP.Region = Region.Center;
TF = new TextField();
TF.ID = "TF";
TF.FieldLabel = "TF";
CB = new ComboBox();
CB.ID = "CB";
CB.FieldLabel = "CB";
CB.Items.Clear();
CB.Items.Add(new ListItem("one", "1"));
CB.Items.Add(new ListItem("two", "2"));
Button test = new Button() { ID = "testbtn", Text = "test" };
test.Listeners.Click.Handler = "App.Store2.load()";
FP.TopBar.Add(new Toolbar() { Items = { test } });
FP.Items.Add(TF);
FP.Items.Add(CB);
GP = new GridPanel();
GP.ID = "GP";
GP.Title = "GP";
GP.Region = Region.East;
GP.Listeners.BeforeRender.Handler = "App.Store1.reload()";
BTN = new Button();
BTN.ID = "BTN";
BTN.Text = "click";
BTN.Icon = Icon.ArrowJoin;
BTN.DirectEvents.Click.Event += new ComponentDirectEvent.DirectEventHandler(Click);
TB = new Toolbar();
TB.Items.Add(BTN);
GP.TopBar.Add(TB);
Store1 = new Store();
Store1.ID = "Store1";
Store1.ReadData += new Store.AjaxReadDataEventHandler(WebFormTest_ReadData);
Model1 = new Model();
Model1.ID = "Model1";
Store1.Model.Add(Model1);
GP.Store.Add(Store1);
TP = new TreePanel();
TP.ID = "TP";
TP.Title = "TP";
TP.Region = Region.East;
TP.RootVisible = false;
TP.Root.Add(new Node() { NodeID = "test", Text = "test" });
Store2 = new TreeStore();
Store2.ID = "Store2";
Store2.ReadData += new TreeStoreBase.ReadDataEventHandler(Store2_ReadData);
TP.Store.Add(Store2);
VP.Items.Add(FP);
//VP.Items.Add(GP);
VP.Items.Add(TP);
if (!X.IsAjaxRequest)
{
CB.Value = "2";
TF.Value = "TEXT";
}
base.OnInitComplete(e);
}
FormPanel FP;
TextField TF;
ComboBox CB;
GridPanel GP;
Button BTN;
Toolbar TB;
Store Store1;
Model Model1;
TreePanel TP;
TreeStore Store2;
protected override void CreateChildControls()
{
base.CreateChildControls();
}
void Store2_ReadData(object sender, NodeLoadEventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!X.IsAjaxRequest)
//{
// this.Store1.DataSource = this.Data;
// this.Store1.DataBind();
//}
}
protected void Refresh(object sender, DirectEventArgs e)
{
}
bool flag = false;
protected void Click(object sender, DirectEventArgs e)
{
GP.GetStore().Reload();
flag = true;
}
protected override void OnPreRender(EventArgs e)
{
if (flag)
{
TF.Value = "asdasd";
}
base.OnPreRender(e);
}
protected void WebFormTest_ReadData(object sender, StoreReadDataEventArgs e)
{
}
private object[] Data
{
get
{
return new object[]
{
new object[] { "3m Co", 71.72, 0.02, 0.03, "9/1 12:00am" },
};
}
}
}
you also can discuss in Ext.net Forums
We committed the change to the SVN trunk. It will go to the next release (v2.3).
The change is similar to your one, but we decided not to change RawValue as well. Thank you for the report and suggested fix.
Fix (ComboBoxBase LoadPostData)
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();

self hosted pushsharp - Events_OnNotificationSendFailure Failure: There were not enough free threads in the ThreadPool to complete the operation

i my PushSharp service is self hosted in windows service,
but after a short while it always throws:
Events_OnNotificationSendFailure
- the exception is "There were not enough free threads in the ThreadPool to complete the operation". what is the proper way to do that?
public partial class PushNotificationService : ServiceBase
{
private static bool flagNotification = true;
static PushService push;
protected override void OnStart(string[] args)
{
SetPushService();
//start console service worker
Thread t = new Thread(NotificationServiceWorker);
t.IsBackground = true;
t.Start();
}
private static void NotificationServiceWorker()
{
try
{
int sendNotificationTimeGap = Convert.ToInt32(ConfigurationManager.AppSettings["SendNotificationTimeGap"]);
while (flagNotification)
{
try
{
/// get IosPushNotificationService
IosPushNotificationService pns = new IosPushNotificationService();
/// Get The New Notification from db
List<NewPushNotifications> notificationToSend = pns.GetIosNotificationsToSend().Where(n => (n.CreatedDate ?? DateTime.Now) > DateTime.Now.AddMinutes(-5)).ToList();
if (notificationToSend != null && notificationToSend.Count > 0)
{
SendNotificationToIphone(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Iphone).ToList());
SendNotificationToAndroid(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Android).ToList());
}
Thread.Sleep(sendNotificationTimeGap);
}
catch (Exception ex)
{
CustomError.Error("error in flagNotification loop", ex);
}
}
}
catch (Exception ex)
{
CustomError.Error("error in NotificationServiceWorker", ex);
}
}
private static void SetPushService()
{
push = new PushService();
push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
push.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
push.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
push.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
string androidSenderId = ConfigurationManager.AppSettings["AndroidSenderId"];
string androidSenderAuthToken = ConfigurationManager.AppSettings["AndroidSenderAuthToken"];
string androidPackage = ConfigurationManager.AppSettings["androidPackage"];
push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings(androidSenderId, androidSenderAuthToken, androidPackage), new PushSharp.Common.PushServiceSettings() { AutoScaleChannels = false });
string appleCertificates = ConfigurationManager.AppSettings["AppleCertificates"];
var appleCert = File.ReadAllBytes(appleCertificates);
var appleCertPassword = ConfigurationManager.AppSettings["AppleCertPassword"];
var appleIsProduction = ConfigurationManager.AppSettings["AppleIsProduction"].ToLower() == bool.TrueString;
push.StartApplePushService(new ApplePushChannelSettings(appleIsProduction, appleCert, appleCertPassword));
}
}
Don't use thread instead you can use timer like this
protected override void OnStart(string[] args)
{
NotificationServiceEventLog.WriteEntry("Service Started at"+DateTime.Now);
if (oNotificationComponent ==null)
oNotificationComponent = new NotificationComponent();
Heading
try
{
if (StartAppleNotificationService())
StartTimer();
}
catch (Exception ex)
{
NotificationServiceEventLog.WriteEntry(ex.Message);
}
base.OnStart(args);
}
private bool StartAppleNotificationService() {
bool IsStarted = false;
try
{
if (oPushService == null)
oPushService = new PushService();
NotificationServiceEventLog.WriteEntry("Apple Notification Service started successfully");
oPushService.Events.OnChannelCreated += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
oPushService.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);
oPushService.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
oPushService.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
oPushService.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
oPushService.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
oPushService.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
byte[] appleCert = File.ReadAllBytes("PushNSCert.p12");
var settings = new ApplePushChannelSettings(true, appleCert, "123456");
oPushService.StartApplePushService(settings);
IsStarted = true;
}
catch (Exception ex)
{
throw new Exception("Exception in starting Apple Service :" + ex.Message + Environment.NewLine + ex.StackTrace);
}
return IsStarted;
}
private bool StartTimer() {
try
{
Double Ms = Convert.ToDouble(ConfigurationManager.AppSettings["TickInterval"]);
NotificationServiceEventLog.WriteEntry("Time Interval" + Ms.ToString());
MyTimer = new Timer();
MyTimer.Interval += (1)*(60)*(1000);
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
}
catch (Exception ex) {
throw ex;
}
return true;
}
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
string SentNotificationIDz = "";
try
{
MyTimer.Enabled = false;
string szConnectionString = #"Server=.\SQL2K8;Database=PaychecksDB_Live;User Id=sa;Password=tdsadmin#321";
//ConfigurationManager.AppSettings["connString"];
lNotifictaion = oNotificationComponent.GetNotificationsList(szConnectionString);
foreach (NotificationModel oNotificationModel in lNotifictaion)
{
SendNotification(oNotificationModel.DeviceToken, oNotificationModel.NotificationMessage + " (" + oNotificationModel.NotificationTitle + ")");
if (SentNotificationIDz == null)
SentNotificationIDz += oNotificationModel.Oid;
else
SentNotificationIDz += "," + oNotificationModel.Oid;
}
oNotificationComponent.DeleteSentNotifications(SentNotificationIDz, szConnectionString);
MyTimer.Enabled = true;
}
catch (Exception ex) {
throw ex;
}
//
}
private void SendNotification(string p_szDeviceToken,string p_szAlert)
{
try
{
oPushService.QueueNotification(NotificationFactory.Apple()
.ForDeviceToken(p_szDeviceToken)
.WithAlert(p_szAlert)
.WithBadge(2)
.WithSound("default")
.WithExpiry(DateTime.Now.AddDays(1))
);
}
catch (Exception ex)
{
throw new Exception("Error in sending Push Notification:" + ex.Message + Environment.NewLine + ex.StackTrace);
}
}

Telerik RadGrid Export to Excel. Missing operand before '=' operator

I am getting the error
Missing operand before '=' operator.
when I try and export and the code is running fine in the grid.
Here is the code for the web part. The error only occurs on the rebind. It works fine in the grid itself. Is there any way to narrow down the exact thing it is erroring on?
I am willing to pay for a support / solution to this problem, I just need it to work.
[Guid("5fbe4ccf-4d90-476b-af77-347de4e1176c")]
public class ParentChildGrid : Microsoft.SharePoint.WebPartPages.WebPart
{
#region
Variables
private bool _error = false;
private string _PageSize = null;
private string _ParentList = null;
private string _ParentView = null;
private string _ParentIDField = null;
private string _FirstChildList = null;
private string _FirstChildView = null;
private string _FirstChildIDField = null;
private string _FirstChildParentIDField = null;
private string _SecondChildList = null;
private string _SecondChildView = null;
private string _SecondChildIDField = null;
private string _SecondChildParentIDField = null;
protected ScriptManager scriptManager;
protected RadAjaxManager ajaxManager;
protected Panel panel;
protected SPView oView;
protected RadGrid oGrid = new RadGrid();
protected Label label;
protected DataTable ParentDataTable;
protected DataTable Child1DataTable;
protected DataTable Child2DataTable;
protected Button cmdExport = new Button();
#endregion
#region
Properties
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("Items Per Page")]
[WebDescription("# of items to include in each page.")]
public string PageSize
{
get
{
if (_PageSize == null)
{
_PageSize = "100";
}
return _PageSize.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("ParentList")]
[WebDescription("Parent List in Grid View")]
public string ParentList
{
get
{
if (_ParentList == null)
{
_ParentList = "";
}
return _ParentList.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("ParentView")]
[WebDescription("View for Parent List")]
public string ParentView
{
get
{
if (_ParentView == null)
{
_ParentView = "";
}
return _ParentView.Trim();
}
set { _ParentView = value.Trim(); }
}
[
Personalizable(PersonalizationScope.Shared)]
[
WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[
WebDisplayName("ParentIDField")]
[
WebDescription("ID Field in Parent List")]
public string ParentIDField
{
get
{
if (_ParentIDField == null)
{
_ParentIDField = "";
}
return _ParentIDField.Trim();
}
set { _ParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("FirstChildList")]
[WebDescription("FirstChildList Name")]
public string FirstChildList
{
get
{
if (_FirstChildList == null)
{
_FirstChildList = "";
}
return _FirstChildList.Trim();
}
set { _FirstChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildView")]
[WebDescription("First Child View Name")]
public string FirstChildView
{
get
{
if (_FirstChildView == null)
{
_FirstChildView = "";
}
return _FirstChildView.Trim();
}
set { _FirstChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildIDField")]
[WebDescription("First Child ID Field (Tyically ID)")]
public string FirstChildIDField
{
get
{
if (_FirstChildIDField == null)
{
_FirstChildIDField = "";
}
return _FirstChildIDField.Trim();
}
set { _FirstChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildParentIDField")]
[WebDescription("First Child Parent ID Field")]
public string FirstChildParentIDField
{
get
{
if (_FirstChildParentIDField == null)
{
_FirstChildParentIDField = "";
}
return _FirstChildParentIDField.Trim();
}
set { _FirstChildParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildList")]
[WebDescription("Second Child List")]
public string SecondChildList
{
get
{
if (_SecondChildList == null)
{
_SecondChildList = "";
}
return _SecondChildList.Trim();
}
set { _SecondChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildView")]
[
WebDescription("Second Child View")]
public string SecondChildView
{
get
{
if (_SecondChildView == null)
{
_SecondChildView = "";
}
return _SecondChildView.Trim();
}
set { _SecondChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildIDField")]
[WebDescription("Second Child ID Field (Typically ID)")]
public string SecondChildIDField
{
get
{
if (_SecondChildIDField == null)
{
_SecondChildIDField = "";
}
return _SecondChildIDField.Trim();
}
set { _SecondChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("SecondChildParentIDField")]
[WebDescription("Second Child ID Field")]
public string SecondChildParentIDField
{
get
{
if (_SecondChildParentIDField == null)
{
_SecondChildParentIDField = "";
}
return _SecondChildParentIDField.Trim();
}
set { _SecondChildParentIDField = value.Trim(); }
}
#endregion
private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript";
private const string EmbeddedScriptFormat = "<script language=javascript>function ByeBye(){ alert('Test Code'); }</script> ";
private const string DisableAjaxScriptKey = "myDisableAjaxIncludeScript";
private const string DisableAjaxForExport = "<script language=javascript>function onRequestStart(sender, args) { if (args.get_eventTarget().indexOf(\"cmdExport\") >= 0);args.set_enableAjax(false);alert('Ajax Disabled'); }</script>";
private void WebPart_ClientScript_PreRender(object sender , System.EventArgs e )
{
if (!Page.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
Page.RegisterClientScriptBlock(ByeByeIncludeScriptKey,
EmbeddedScriptFormat);
if (!Page.IsClientScriptBlockRegistered(DisableAjaxScriptKey))
Page.RegisterClientScriptBlock(DisableAjaxScriptKey,
DisableAjaxForExport);
//ajaxManager.ClientEvents.OnRequestStart = "onRequestStart";
}
public ParentChildGrid()
{
this.ExportMode = WebPartExportMode.All;
this.PreRender += new EventHandler(WebPart_ClientScript_PreRender);
}
private void onRequestStart()
{
ajaxManager.EnableAJAX =
false;
}
protected override void OnInit(EventArgs e)
{
try
{
base.OnInit(e);
Page.ClientScript.RegisterStartupScript(
typeof(ParentChildGrid), this.ID, "_spOriginalFormAction = document.forms[0].action;_spSuppressFormOnSubmitWrapper=true;", true);
if (this.Page.Form != null)
{
string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
{
this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
}
}
scriptManager =
ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
scriptManager =
new RadScriptManager();
this.Page.Form.Controls.AddAt(0, scriptManager);
}
scriptManager.RegisterPostBackControl(cmdExport);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnLoad(EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport);
if (!_error)
{
try
{
base.OnLoad(e);
this.EnsureChildControls();
base.OnLoad(e);
if (_ParentList != null)
{
if (_ParentList != "")
{
panel =
new Panel();
panel.ID =
"Panel1";
this.Controls.Add(panel);
oGrid =
new RadGrid();
DefineComplexGrid();
oGrid.GridExporting +=
new OnGridExportingEventHandler(oGrid_GridExporting);
panel.Controls.Add(oGrid);
//DefineSimpleMasterDetail();
cmdExport.Click +=
new EventHandler(cmdExport_Click);
cmdExport.Text =
"Export";
Button cmdExpandAll = new Button();
cmdExpandAll.Text =
"Expand All";
cmdExpandAll.Click +=
new EventHandler(cmdExpandAll_Click);
panel.Controls.Add(cmdExpandAll);
ajaxManager =
RadAjaxManager.GetCurrent(this.Page);
if (ajaxManager == null)
{
ajaxManager =
new RadAjaxManager();
ajaxManager.ID =
"RadAjaxManager1";
Controls.Add(ajaxManager);
this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);
}
ajaxManager.AjaxSettings.AddAjaxSetting(oGrid, panel);
panel.Controls.Add(cmdExport);
ajaxManager.AjaxRequest +=
new RadAjaxControl.AjaxRequestDelegate(ajaxManager_AjaxRequest);
this.Controls.Add(new LiteralControl("<br><br><input class='ms-SPButton' value=\'Test Code\' type=button onclick=\"ByeBye();\" >"));
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
void oGrid_GridExporting(object source, GridExportingArgs e)
{
//throw new NotImplementedException();
}
void ajaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
ajaxManager.EnableAJAX =
false;
}
void cmdExpandAll_Click(object sender, EventArgs e)
{
try
{
foreach (GridItem item in oGrid.MasterTableView.Items)
{
item.Expanded =
true;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void cmdExport_Click(object sender, EventArgs e)
{
try
{
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
oGrid.ExportSettings.ExportOnlyData =
true;
oGrid.ExportSettings.IgnorePaging =
true;
oGrid.ExportSettings.OpenInNewWindow =
true;
oGrid.MasterTableView.HierarchyDefaultExpanded =
true;
if (FirstChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[0].HierarchyDefaultExpanded =
true;
if (SecondChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[1].HierarchyDefaultExpanded =
true;
oGrid.Rebind();
oGrid.MasterTableView.ExportToExcel();
}
catch (Exception ex)
{
HandleException(ex);
}
}
//private void DefineSimpleGrid()
//{
// try
// {
// oGrid.ID = "Master";
// oGrid.PageSize = 10;
// oGrid.AllowPaging = true;
// oGrid.AllowSorting = true;
// oGrid.Skin = "WebBlue";
// oGrid.GroupingEnabled = true;
// oGrid.NeedDataSource += new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
// oGrid.ShowStatusBar = true;
// oGrid.ShowGroupPanel = true;
// oGrid.GroupingEnabled = true;
// oGrid.ClientSettings.AllowDragToGroup = true;
// oGrid.ClientSettings.AllowColumnsReorder = true;
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private DataTable GetDataTable(String cListName, String ViewName)
{
try
{
SPList list = SPContext.Current.Web.Lists[cListName];
SPView view = list.Views[ViewName];
SPListItemCollection items = list.GetItems(view);
if (items != null)
{
if (items.Count > 0)
return items.GetDataTable();
}
}
catch (Exception ex)
{
HandleException(ex);
}
return null;
}
//private void DefineSimpleMasterDetail()
//{
// try
// {
// oGrid.MasterTableView.DataKeyNames = new string[] { "ID" };
// oGrid.Skin = "Default";
// oGrid.Width = Unit.Percentage(100);
// oGrid.PageSize = 5;
// oGrid.AllowPaging = true;
// oGrid.MasterTableView.PageSize = 15;
// oGrid.MasterTableView.DataSource = GetDataTable(_ParentList, _ParentView);
// GridTableView tableViewOrders = new GridTableView(oGrid);
// tableViewOrders.DataSource = GetDataTable(_FirstChildList, _FirstChildView);
// tableViewOrders.DataKeyNames = new string[] { _ParentIDField };
// GridRelationFields relationFields = new GridRelationFields();
// relationFields.MasterKeyField = _FirstChildIDField;
// relationFields.DetailKeyField = _FirstChildParentIDField;
// tableViewOrders.ParentTableRelation.Add(relationFields);
// oGrid.MasterTableView.DetailTables.Add(tableViewOrders);
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private void DefineComplexGrid()
{
try
{
oGrid.ID =
"RadGrid1";
//oGrid.Width = Unit.Percentage(98);
oGrid.PageSize =
Convert.ToInt32(PageSize);
oGrid.AllowPaging =
true;
oGrid.AllowSorting =
true;
oGrid.PagerStyle.Mode =
GridPagerMode.NextPrevAndNumeric;
oGrid.ShowStatusBar =
true;
oGrid.ClientSettings.Resizing.AllowColumnResize =
true;
oGrid.DetailTableDataBind +=
new GridDetailTableDataBindEventHandler(oGrid_DetailTableDataBind);
oGrid.NeedDataSource +=
new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
oGrid.ColumnCreated +=
new GridColumnCreatedEventHandler(oGrid_ColumnCreated);
oGrid.MasterTableView.Name = _ParentList;
if (_FirstChildList != "" || _SecondChildList != "")
{
oGrid.MasterTableView.PageSize =
Convert.ToInt32(PageSize);
oGrid.MasterTableView.DataKeyNames =
new string[] { _ParentIDField };
oGrid.MasterTableView.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
}
if (_FirstChildList != "")
{
GridTableView tableViewFirstChild = new GridTableView(oGrid);
tableViewFirstChild.Width =
Unit.Percentage(100);
tableViewFirstChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewFirstChild.DataKeyNames =
new string[] { _FirstChildIDField };
tableViewFirstChild.Name = _FirstChildList;
GridRelationFields FirstChildrelationFields = new GridRelationFields();
FirstChildrelationFields.MasterKeyField = _ParentIDField;
FirstChildrelationFields.DetailKeyField = _FirstChildParentIDField;
tableViewFirstChild.ParentTableRelation.Add(FirstChildrelationFields);
tableViewFirstChild.Caption = _FirstChildList;
oGrid.MasterTableView.DetailTables.Add(tableViewFirstChild);
}
if (_SecondChildList != "")
{
GridTableView tableViewSecondChild = new GridTableView(oGrid);
tableViewSecondChild.Width =
Unit.Percentage(100);
tableViewSecondChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewSecondChild.DataKeyNames =
new string[] { _SecondChildIDField };
tableViewSecondChild.Name = _SecondChildList;
GridRelationFields SecondChildrelationFields = new GridRelationFields();
SecondChildrelationFields.MasterKeyField = _ParentIDField;
SecondChildrelationFields.DetailKeyField = _SecondChildParentIDField;
tableViewSecondChild.Caption = _SecondChildList;
tableViewSecondChild.ParentTableRelation.Add(SecondChildrelationFields);
oGrid.MasterTableView.DetailTables.Add(tableViewSecondChild);
}
oGrid.ShowStatusBar =
true;
oGrid.ShowGroupPanel =
true;
oGrid.GroupingEnabled =
true;
oGrid.ClientSettings.AllowDragToGroup =
true;
oGrid.ClientSettings.AllowColumnsReorder =
true;
oGrid.Skin =
"Web20";
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
try
{
//if (e.Column.HeaderText == "ID" || e.Column.HeaderText == "Created")
//{
// e.Column.Display = false;
// return;
//}
String cOwnerTable = "";
cOwnerTable = e.OwnerTableView.Name;
if (cOwnerTable.Trim() != "" && e.Column.HeaderText != "" && e.Column.HeaderText != _FirstChildParentIDField && e.Column.HeaderText != _SecondChildParentIDField)
{
SPList CurrentList = SPContext.Current.Web.Lists[e.OwnerTableView.Name];
e.Column.HeaderText = GetFieldDisplayName(e.Column.HeaderText, CurrentList);
SPField oField = CurrentList.Fields[e.Column.HeaderText];
GridBoundColumn col = (GridBoundColumn)e.Column;
switch (oField.Type)
{
case SPFieldType.Currency:
col.DataFormatString =
"{0:C}";
break;
case SPFieldType.DateTime:
SPFieldDateTime oDateTime = (SPFieldDateTime)oField;
if (oDateTime.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
col.DataFormatString =
"{0:d}";
break;
default:
break;
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private DataTable GetChildDataTable(GridDetailTableDataBindEventArgs e, String cChildListName, String cChildView,String cParentIDField)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
SPList FirstChildList = SPContext.Current.Web.Lists[cChildListName];
SPView oView = FirstChildList.Views[cChildView];
String cContractID = parentItem[_ParentIDField].Text;
SPQuery oChildQuery = new SPQuery();
if (Occurs(cParentIDField, oView.Query) == 2)
{
String cNewQuery = oView.Query;
Int32 iPos = cNewQuery.IndexOf(cParentIDField) + cParentIDField.Length;
String cPartOne = cNewQuery.Substring(0,cNewQuery.IndexOf(cParentIDField, iPos));
String cPartTwo = cNewQuery.Substring(cNewQuery.IndexOf(cParentIDField, iPos) + cParentIDField.Length);
cNewQuery = cPartOne + cContractID + cPartTwo;
oChildQuery.Query = cNewQuery;
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
else
{
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
SPViewFieldCollection oViewFields = oView.ViewFields;
oViewFields.Add(cParentIDField);
String cViewFields = oViewFields.SchemaXml;
oChildQuery.ViewFields = cViewFields;
SPListItemCollection items = FirstChildList.GetItems(oChildQuery);
if (items != null)
{
if (items.Count > 0)
{
return items.GetDataTable();
}
}
}
catch (Exception ex)
{
//HandleException(ex);
}
return null;
}
void oGrid_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
if (parentItem.Edit)
{
return;
}
if (e.DetailTableView.Name == _FirstChildList)
{
Child1DataTable = GetChildDataTable(e, _FirstChildList, _FirstChildView, _FirstChildParentIDField);
e.DetailTableView.DataSource = Child1DataTable;
}
if (e.DetailTableView.Name == _SecondChildList)
{
Child2DataTable = GetChildDataTable(e, _SecondChildList, _SecondChildView, _SecondChildParentIDField);
e.DetailTableView.DataSource = Child2DataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
if (!e.IsFromDetailTable)
{
SPList ParentList = SPContext.Current.Web.Lists[_ParentList];
oView = ParentList.Views[_ParentView];
SPQuery ParentQuery = new SPQuery();
ParentQuery.Query = oView.Query;
ParentQuery.RowLimit = 100000;
ParentQuery.ViewFields = oView.ViewFields.SchemaXml;
SPListItemCollection oItems = SPContext.Current.Web.Lists[_ParentList].GetItems(ParentQuery);
ParentDataTable = oItems.GetDataTable();
oGrid.DataSource = ParentDataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private string GetFieldDisplayName(String cInternalName, SPList oList)
{
try
{
foreach (SPField field in oList.Fields)
{
if (field.InternalName == cInternalName)
return field.Title;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return cInternalName;
}
private Int32 Occurs(String SearchFor, String SearchIn)
{
Int32 Count = 0;
Int32 iPos = 0;
try
{
while (SearchIn.IndexOf(SearchFor, iPos) != -1)
{
Count++;
iPos = SearchIn.IndexOf(SearchFor, iPos) + 1;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return Count;
}
private void HandleException(Exception ex)
{
this._error = true;
try
{
this.Controls.Clear();
this.Controls.Add(new LiteralControl(ex.Message));
}
catch
{
}
}
} //End Class
As a follow-up, it appears the problem was that there were NULL values in John's original data. These nulls were causing problems during the data export. Fixing the null values also fixed the Excel export. Original solution on Telerik.com forums:
http://www.telerik.com/community/forums/aspnet-ajax/grid/extremely-frustrated-please-help-with-radgrid-export-of-multi-tabe-view.aspx

Resources