I'm trying to update information in the SQL table with this code using c# language, the first section is to count all data. the second section is to run my update Query/function
the event is : private void mlnk_ADD_Click(object sender, EventArgs e)
string SARL;
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [employe] WHERE CODE = #CODE OR FULLNAME =
#FULLNAME OR BIRTHDATE = #BIRTHDATE OR BIRTHPLACE = #BIRTHPLACE OR ADDRESS = #ADDRESS
OR NCCP = #NCCP OR PHONE = #PHONE OR JOB = #JOB OR SARL =#SARL", napster.myConn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#CODE", mtb_CODE.Text);
cmd.Parameters.AddWithValue("#FULLNAME", mtb_FULLNAME.Text);
cmd.Parameters.AddWithValue("#BIRTHDATE", mdtp_BIRTHDATE.Text);
cmd.Parameters.AddWithValue("#BIRTHPLACE", mtb_BIRTHPLACE.Text);
cmd.Parameters.AddWithValue("#ADDRESS", mtb_ADDRESS.Text);
cmd.Parameters.AddWithValue("#NCCP", mtb_NCCP.Text);
cmd.Parameters.AddWithValue("#PHONE", mtb_PHONE.Text);
cmd.Parameters.AddWithValue("#JOB", mtb_JOB.Text);
if (mrb_LOCATERR.Checked == true)
{ SARL = "LOCA-TERR"; }
if (mrb_LUDAR.Checked == true)
{ SARL = "LUDAR"; }
if (mrb_ECORA.Checked == true)
{ SARL = "ECORA"; }
cmd.Parameters.AddWithValue("#SARL", SARL);
int UserExist = (int)cmd.ExecuteScalar();
here I am trying to insert the data into my table after checking that all data not exist to avoid the duplicate
if (UserExist > 0)
{
this.Alert("the information already exists.", frmAlert.alertTypeEnum.Error);
}
else
{
if (mrb_LOCATERR.Checked == true)
{ SARL = "LOCA-TERR"; }
if (mrb_LUDAR.Checked == true)
{ SARL = "LUDAR"; }
if (mrb_ECORA.Checked == true)
{ SARL = "ECORA"; }
if (mtb_CODE.Text != "" && mtb_FULLNAME.Text != "" && mdtp_BIRTHDATE.Text != "" && mtb_BIRTHPLACE.Text != "" && mtb_JOB.Text != "" && mtb_PHONE.Text != "")
{
// (update_employee) is public void for insert data into [employe] table
napster.update_employee(mlnk_ID.Text, mtb_CODE.Text, mtb_FULLNAME.Text, mdtp_BIRTHDATE.Text, mtb_BIRTHPLACE.Text, mtb_ADDRESS.Text, mtb_JOB.Text, mtb_PHONE.Text, SARL, mtb_NCCP.Text);
mlnk_ID.Text = "";
mtb_CODE.Text = "";
mtb_FULLNAME.Text = "";
mdtp_BIRTHDATE.Text = "";
mtb_BIRTHPLACE.Text = "";
mtb_ADDRESS.Text = "";
mtb_JOB.Text = "";
mtb_PHONE.Text = "";
mtb_NCCP.Text = "";
mrb_LOCATERR.Checked = true;
this.Alert("information updated.", frmAlert.alertTypeEnum.Info);
}
else
{
this.Alert("information not updated.", frmAlert.alertTypeEnum.Error);
}
}
Use stored procedure its more cleanner and you can define the output and the input parameteres ( exemple :select cout(*) into output_parameter where ....).
and use switch statement, There is a lot of IF in your code.
When i run my application i get an error that not all the fields of the table tblContact are filled. How do i edit in my code that if a record is null I show in my application null.
Here is my code:
public void SelID(int Zoek)
{
string SQL = "select * from tblContact";
SQL += " where cNr=" + Zoek.ToString();
DataTable DT = Database.ExecSelect(SQL);
if (DT.Rows.Count == 0)
{
pr_cNr = -1;
}
else
{
pr_cNr = (int)(DT.Rows[0]["cNr"]);
pr_cVNaam = (string)(DT.Rows[0]["cVnaam"]);
pr_cTNaam = (string)(DT.Rows[0]["cTNaam"]);
pr_cANaam = (string)(DT.Rows[0]["cAnaam"]);
pr_cAdres = (string)(DT.Rows[0]["cAdres"]);
pr_cPost = (string)(DT.Rows[0]["cPost"]);
pr_cPlaats = (string)(DT.Rows[0]["cPlaats"]);
}
}
try this way:
object val = row["ColumnName"];
if (val == DBNull.Value)
// your code
else
//your code
using inline checking for all columns makes your code messy and error-prone.
It seems, you have to check for null:
...
else
{
// In case of integer we have to specify how null should be treated:
pr_cNr = DT.Rows[0].IsNUll("cNr")
? -1 // or whatever default value
: Convert.ToInt32(DT.Rows[0]["cNr"]);
// In case of string Convert.ToString(DBNull.Value) returns empty string ""
// Please, notice that original (string) (DBNull.Value) throws exception
pr_cVNaam = Convert.ToString(DT.Rows[0]["cVnaam"]);
pr_cTNaam = Convert.ToString(DT.Rows[0]["cTNaam"]);
pr_cANaam = Convert.ToString(DT.Rows[0]["cAnaam"]);
pr_cAdres = Convert.ToString(DT.Rows[0]["cAdres"]);
pr_cPost = Convert.ToString(DT.Rows[0]["cPost"]);
pr_cPlaats = Convert.ToString(DT.Rows[0]["cPlaats"]);
}
I am quite poor at writing code, hence the question. Below I am adding items into a SharePoint List from a DB while checking if any of the fields contains DBNulls. Rather than having to perform the check for each column like I am below, can someone help me to put it in a loop if possible? I would be forever grateful
using (OdbcConnection connection = new OdbcConnection())
{
connection.ConnectionString = "dsn=abc;uid=xyz;pwd=yuo;DataSource=aaa";
connection.ConnectionTimeout = 100;
connection.Open();
OdbcCommand command_donor = new OdbcCommand("Select * From vw_SP_aaa_bbb", connection);
try
{
using (OdbcDataReader reader = command_donor.ExecuteReader())
{
while (reader.Read())
{
var obj0 = reader.GetValue(48);
var obj1 = reader.GetValue(0);
var obj2 = reader.GetValue(33);
var obj3 = reader.GetValue(47);
var obj4 = reader.GetValue(42);
var obj5 = reader.GetValue(42);
ListItem oListItem_aaa = oList_aaa .AddItem(itemCreateInfo);
if (obj0 == null || obj0.Equals(DBNull.Value))
{ oListItem_aaa["Title"] = ""; }
else
{ oListItem_aaa["Title"] = reader.GetString(48).ToString(); }
if (obj1 == null || obj1.Equals(DBNull.Value))
{ oListItem_aaa["aaa_x0020_ID"] = ""; }
else
{ oListItem_aaa["aaa_x0020_ID"] = reader.GetString(0).ToString(); }
if (obj2 == null || obj2.Equals(DBNull.Value))
{ oListItem_aaa["Excluded_x0020_By"] = ""; }
else
{ oListItem_aaa["Excluded_x0020_By"] = reader.GetString(33).ToString(); }
if (obj3 == null || obj3.Equals(DBNull.Value))
{ oListItem_aaa["Excluded_x0020_On"] = ""; }
else
{ oListItem_aaa["Excluded_x0020_On"] = reader.GetDateTime(47).ToString("MM/dd/yyyy"); }
if (obj4 == null || obj4.Equals(DBNull.Value))
{ oListItem_aaa["Reason"] = ""; }
else
{ oListItem_aaa["Reason"] = reader.GetString(42).Substring(50, reader.GetString(42).ToString().Length-50); }
if (obj5 == null || obj5.Equals(DBNull.Value))
{ oListItem_aaa["Publish"] = ""; }
else
{ oListItem_aaa["Publish"] = reader.GetString(42).Substring(50, reader.GetString(42).ToString().Length - 50); }
oListItem_aaa.Update();
context.ExecuteQuery();
}
}
}
catch (Exception exception)
{
Console.WriteLine("The Error is:" + exception);
Console.ReadLine();
}
}
Use Short IIF like
oListItem_aaa["Excluded_x0020_By"] = (obj1 == null || obj1.Equals(DBNull.Value)) ? "" : reader.GetString(0).ToString();
or
var obj0 = (reader.GetValue(48) != DBNull.Value && !String.IsNullOrEmpty(Convert.ToString(reader.GetValue(48)))) ? reader.GetValue(48) : "");
in one line. Then you dont need to use the if then else's... described also in MSDN at Operator ?: (C#-Referenz).
Note:-The Question pertains to ASP.NET and C#.
I have 3 functions
GetDataBySearchCriteria.
GetData.
GetGridData.
The first function is called when page is loaded. The second function gets called when the user makes a change on page and and presses a btn (GetData) where I set the Session Variable which holds the Search Criteria Data as GridData Object. The Third function is called by the second function to get data as a GridData Object where GridData is a user defined class. Later in the calling function it is converted to json object which is used to render a grid table(jqgrid).
Problem:- We maintain the session in order to facilitate a temporary search criteria holder which we use when the intended user navigates from one page to another in the same module. In my code I set the Session variable only when user presses GetData and according to the current requirement I had to put hard code changes to change the data I get from session for particular pages. In doing so the Session Data is automatically changing. I am unable to figure out why. please help.
Here's the code :-
[System.Web.Services.WebMethod]
public static string GetDataBySearchCriteria(int ReportID) // called when page is loaded
{
if (SessionVariables.RoleID == 0)
{
return "null";
}
try
{
SetProperties(ReportID);
if (!CheckAuthorization(ReportID)) // write ! before statement after testing if its not written
{
return "null";
}
else
{
#region else part
HttpContext.Current.Session["ReportID"] = ReportID;
if (HttpContext.Current.Session["SalesUserSession"] != null)
{
SetProperties(ReportID);
GridData gd = new GridData();
gd = HttpContext.Current.Session["SalesUserSession"] as GridData;
if (pagetitle.ToLower() == "top referring practices")
{
gd.RowArea = "Referring Practice";
gd.order = "Month13#desc";
gd.SelectedCpt = "";
gd.SelectedLocation = "";
gd.SelectedModality = "";
gd.SelectedReferringPractice = "";
gd.SelectedPhysicians = "";
//gd.direction = "desc";
}
else if (pagetitle.ToLower() == "top referring physicians")
{
gd.RowArea = "Physician";
gd.order = "Month13#desc";
gd.SelectedCpt = "";
gd.SelectedLocation = "";
gd.SelectedModality = "";
gd.SelectedReferringPractice = "";
gd.SelectedPhysicians = "";
//gd.direction = "desc";
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(GetGridData(isVolume: gd.IsVolume, pageNumber: 1, pageSize: gd.PageSize, rowArea: gd.RowArea, cpt: gd.SelectedCpt, referringPhysician: gd.SelectedPhysicians, referringPractice: gd.SelectedReferringPractice, speciality: gd.SelectedSpeciality, modalityFilter: gd.SelectedModality, locationFilter: gd.SelectedLocation, practice: gd.SelectedPractice,order:gd.order,orderBy:gd.orderBy,direction:gd.direction,orderBySummary:gd.orderBySummary,OrderBySummaryCol:gd.orderBySummaryCol,ShowSubTotalForAllGroup: gd.ShowSubTotalForAllGroup));//,direction:gd.direction,orderBySummary:"",OrderBySummaryCol:""));
}
else
{
SqlParameter[] parameters = new SqlParameter[3]; // Error Line
parameters[0] = new SqlParameter("#UserId", SqlDbType.Int);
parameters[0].Value = SessionVariables.UserID;
parameters[1] = new SqlParameter("#RoleID", SqlDbType.Int);
parameters[1].Value = SessionVariables.RoleID;
parameters[2] = new SqlParameter("#ReportTitle", SqlDbType.NVarChar);
// Below Code Added on 11/05/2015 (dd/mm/yyyy) for Testing Purposes
//if (pagetitle == "Top Referring Practices" || pagetitle == "Top Referring Physicians")
//{
// //pagetitle = "Trending Report";
//}
// Modification Ends 11/05/2015
parameters[2].Value = pagetitle;
GridData gridData = new GridData();
DataSet ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.StoredProcedure, "Sales_GetDataByDefaultSearch", parameters);
DataTable Datadt = ds.Tables[1];
if (ReportID == 1 && ds.Tables.Count > 3)
{
//holidayList = ds.Tables[3].AsEnumerable().Select(r=>r.Field<string>("NonWorkingDays")).ToArray();
}
StringBuilder sbcol = new StringBuilder();
sbcol.Append("[");
foreach (DataColumn column in Datadt.Columns)
{
sbcol.Append("\"").Append(GetPivotColumnName(column.ColumnName)).Append("\",");
}
sbcol.Remove(sbcol.Length - 1, 1).Append("]");
StringBuilder sbcolModel = new StringBuilder();
sbcolModel.Append("[");
string[] rowAreaFields = ds.Tables[0].Rows[0]["RowArea"].ToString().Split(',');
//string rowArea;
//rowArea = string.Join(",", rowAreaFields);
foreach (DataColumn column in Datadt.Columns)
{
//if (rowAreaFields.Contains(column.ColumnName.Trim()) && column.ColumnName != null)
if (rowAreaFields.Any(s => column.ColumnName.Trim().Contains(s)))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"colstyle\",\"align\":\"left\",\"sortable\":true,\"frozen\":true},");
}
//else if (holidayList.Contains(column.ColumnName.Trim()) && column.ColumnName != null)
//{
// sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"holidaystyle\",\"align\":\"right\",\"width\":\"70px\"},");
//}
else if (column.Ordinal >= Datadt.Columns.Count - NoofSummaryColumns)
{
if (PosNegSummaryValues.Contains(Datadt.Columns.Count - column.Ordinal))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"PosNegValue\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else
{
if (column.ColumnName.Contains(" Actual"))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"120px\"},");
}
}
}
else
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"align\":\"right\",\"width\":\"70px\"},");
}
}
sbcolModel.Remove(sbcolModel.Length - 1, 1);
sbcolModel.Append("]");
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> drow;
foreach (DataRow dr in Datadt.Rows)
{
drow = new Dictionary<string, object>();
foreach (DataColumn col in Datadt.Columns)
{
drow.Add(GetPivotColumnName(col.ColumnName), dr[col]);
}
rows.Add(drow);
}
StringBuilder sbjsonRows = new StringBuilder();
sbjsonRows.Append(serializer.Serialize(rows));
StringBuilder json = new StringBuilder();
json.Append("{").Append("\"rows\":").Append(sbjsonRows.ToString().Trim()).Append("}");
json.ToString();
string[] GroupAreaSortOrderArray;
string[] SummarySortOrderArray;
foreach (DataRow dr in ds.Tables[0].Rows)
{
gridData.isReportDefault = dr["IsDefault"] == DBNull.Value ? false : Convert.ToBoolean(dr["IsDefault"]);
gridData.isAllReportDefault = dr["IsAllReportDefault"] == DBNull.Value ? false : Convert.ToBoolean(dr["IsAllReportDefault"]);
gridData.IsVolume = dr["IsVolume"] == DBNull.Value ? true : Convert.ToBoolean(dr["IsVolume"]);
gridData.RowArea = dr["RowArea"] == DBNull.Value ? "Modality" : GetRowAreaForPivot(Convert.ToString(dr["RowArea"]));
gridData.TitleName = dr["TitleName"] == DBNull.Value ? "" : Convert.ToString(dr["TitleName"]);
gridData.SelectedPractice = dr["PracticeFilter"] == DBNull.Value ? "" : Convert.ToString(dr["PracticeFilter"]);
gridData.SelectedModality = dr["ModalityFilter"] == DBNull.Value ? "" : Convert.ToString(dr["ModalityFilter"]).Replace("'","");
gridData.SelectedLocation = dr["LocationFilter"] == DBNull.Value ? "" : Convert.ToString(dr["LocationFilter"]);
gridData.SelectedCpt = dr["CptFilter"] == DBNull.Value ? "" : Convert.ToString(dr["CptFilter"]).Replace("'","");
gridData.SelectedPhysicians = dr["ReferringPhysicianFilter"] == DBNull.Value ? "" : Convert.ToString(dr["ReferringPhysicianFilter"]);
gridData.SelectedReferringPractice = dr["ReferringPracticeFilter"] == DBNull.Value ? "" : Convert.ToString(dr["ReferringPracticeFilter"]);
gridData.SelectedSpeciality = dr["SpecialityFilter"] == DBNull.Value ? "" : Convert.ToString(dr["SpecialityFilter"]);
gridData.PageSize = dr["PageSize"] == DBNull.Value ? 30 : Convert.ToInt32(dr["PageSize"]);
gridData.ScheduledReport = dr["IsReportScheduled"] == DBNull.Value ? false : Convert.ToBoolean(dr["IsReportScheduled"]);
gridData.Daily = dr["Daily"] == DBNull.Value ? false : Convert.ToBoolean(dr["Daily"]);
gridData.Weekly = dr["Weekly"] == DBNull.Value ? -1 : Convert.ToInt32(dr["Weekly"]);
gridData.Monthly = dr["Monthly"] == DBNull.Value ? 0 : Convert.ToInt32(dr["Monthly"]);
gridData.SelectedPracticeName = dr["PracticeName"] == DBNull.Value ? "" : Convert.ToString(dr["PracticeName"]);
gridData.ShowSubTotalForAllGroup = dr["ShowSubTotalForAllGroup"] == DBNull.Value ? "False" : Convert.ToString(dr["ShowSubTotalForAllGroup"]);
//remap the db column to its corresponding Pivot column here
GroupAreaSortOrderArray = Convert.ToString(dr["GroupAreaSortOrder"]).Split('#');
SummarySortOrderArray = Convert.ToString(dr["SummarySortOrder"]).Split('#');
gridData.order = dr["order"] == DBNull.Value ? "" : Convert.ToString(dr["order"]);
if (GroupAreaSortOrderArray[0] != "")
{
gridData.orderBy = GroupAreaSortOrderArray[0] == null ? "" : MapDbColumnsToPivot(GroupAreaSortOrderArray[0], Datadt);
gridData.direction = GroupAreaSortOrderArray[1] == null ? "" : MapDbColumnsToPivot(GroupAreaSortOrderArray[1], Datadt);
}
if (SummarySortOrderArray[0] != "")
{
gridData.orderBySummary = SummarySortOrderArray[0] == null ? "" : MapDbColumnsToPivot(SummarySortOrderArray[0], Datadt);
gridData.orderBySummaryCol = SummarySortOrderArray[1] == null ? "" : MapDbColumnsToPivot(SummarySortOrderArray[1], Datadt);
}
//gridData.orderBy = gridData.order == "" ? "" :gridData.order.Split('#')[0];
//gridData.direction = gridData.direction==""?"" :gridData.order.Split('#')[1];
//gridData.Date = dr["Date"] == DBNull.Value ? "" : Convert.ToDateTime(dr["Date"]).ToString("yyyy-MM-dd");
}
gridData.page = 1;
gridData.total = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(ds.Tables[2].Rows[0][0]) / Convert.ToDouble(ds.Tables[0].Rows[0]["PageSize"])));
gridData.records = Convert.ToInt32(ds.Tables[2].Rows[0][0]);
gridData.col = sbcol.ToString();
gridData.colModel = sbcolModel.ToString();
gridData.rows = sbjsonRows.ToString().Trim();
return serializer.Serialize(gridData);
}
#endregion
//}
}
}
catch (Exception ex)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
throw;
}
}
[System.Web.Services.WebMethod]
public static string GetData(bool isVolume, int pageNumber, int pageSize, string rowArea, string specialityFilter, string modalityFilter, string locationFilter, string CptFilters, string referringpracticeFilter, string referringphysiciansFilter, int ReportID, string practiceFilter, string order, string orderBy, string direction, int SearchTitleID, string orderBySummary, string orderBySummaryCol, string ShowSubTotalForAllGroup)
{
try
{
if (HttpContext.Current.Session["RoleID"] == null || SessionVariables.RoleID == 0 || SessionVariables.UserID == 0)
{
return "null";
}
else
{
if (practiceFilter == null || practiceFilter == "")
{
practiceFilter = "1";
}
System.Collections.SortedList SystemSearchTitleIDs = new System.Collections.SortedList();
SystemSearchTitleIDs = (System.Collections.SortedList)HttpContext.Current.Session["SystemSearchTitleIds"];
SetProperties(ReportID);
HttpContext.Current.Session["ReportID"] = ReportID;
GridData gd;
string[] orderArray;
if (order.Trim() != string.Empty)
{
orderArray = order.Split('#');
orderArray[0] = SalesColumnMapper(orderArray[0]);
order = orderArray[0] + "#" + orderArray[1];
}
gd = GetGridData(isVolume: isVolume, pageNumber: pageNumber, pageSize: pageSize, rowArea: rowArea, modalityFilter: modalityFilter, locationFilter: locationFilter, referringPhysician: referringphysiciansFilter, referringPractice: referringpracticeFilter, speciality: specialityFilter, cpt: CptFilters, practice: practiceFilter, order: order, orderBy: orderBy, direction: direction, orderBySummary: orderBySummary, OrderBySummaryCol: orderBySummaryCol, ShowSubTotalForAllGroup: ShowSubTotalForAllGroup);
HttpContext.Current.Session["SalesUserSession"] = gd;
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(gd);
}
}
catch (Exception ex)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
throw;
}
}
private static GridData GetGridData(bool isVolume, int pageNumber, int pageSize, string rowArea, string modalityFilter, string locationFilter, string referringPhysician, string referringPractice, string speciality, string cpt, string practice, string order,string orderBy, string direction, string orderBySummary, string OrderBySummaryCol,string ShowSubTotalForAllGroup)
{
try
{
string[] rowAreaFields = rowArea.Split(',').Select(field => field.Trim()).ToArray();
DataSet ds = GetDataByFilterCriteria(isVolume: isVolume, pageNumber: pageNumber, pageSize: pageSize, rowArea: rowArea, modalityFilter: modalityFilter, locationFilter: locationFilter, referringPhysician: referringPhysician, referringPractice: referringPractice, speciality: speciality, cpt: cpt, practice: practice, order: order, ShowSubTotalForAllGroup: ShowSubTotalForAllGroup);
DataTable Datadt = ds.Tables[0];
StringBuilder sbcol = new StringBuilder();
sbcol.Append("[");
foreach (DataColumn column in Datadt.Columns)
{
sbcol.Append("\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",");
}
sbcol.Remove(sbcol.Length - 1, 1);
sbcol.Append("]");
StringBuilder sbcolModel = new StringBuilder();
sbcolModel.Append("[");
foreach (DataColumn column in Datadt.Columns)
{
if (rowAreaFields.Any(s => GetPivotColumnName(column.ColumnName.Trim()).Contains(s)))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"colstyle\",\"align\":\"left\",\"sortable\":true,\"frozen\":true},");
}
else if (column.Ordinal >= Datadt.Columns.Count - NoofSummaryColumns)
{
if (PosNegSummaryValues.Contains(Datadt.Columns.Count - column.Ordinal))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"PosNegValue\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else
{
if (column.ColumnName.Contains(" Actual"))
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"70px\"},");
}
else {
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"classes\":\"SummaryColumns\",\"align\":\"right\",\"sortable\":true,\"width\":\"120px\"},");
}
}
}
else
{
sbcolModel.Append("{\"name\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"index\":\"").Append(GetPivotColumnName(column.ColumnName.Trim())).Append("\",\"align\":\"right\",\"width\":\"70px\"},");
}
}
sbcolModel.Remove(sbcolModel.Length - 1, 1);
sbcolModel.Append("]");
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> drow;
foreach (DataRow dr in Datadt.Rows)
{
drow = new Dictionary<string, object>();
foreach (DataColumn col in Datadt.Columns)
{
drow.Add(GetPivotColumnName(col.ColumnName), dr[col]);
}
rows.Add(drow);
}
StringBuilder sbjsonRows = new StringBuilder();
sbjsonRows.Append(serializer.Serialize(rows));
StringBuilder json = new StringBuilder();
json.Append("{");
json.Append("\"rows\":");
json.Append(sbjsonRows.ToString().Trim());
json.Append("}");
json.ToString();
GridData gridData = new GridData();
gridData.SelectedPractice = practice; // New statement returns practicefilter -- if grid displays this we can remove it
gridData.SelectedLocation = locationFilter;
gridData.SelectedModality = modalityFilter;
gridData.SelectedReferringPractice = referringPractice;
gridData.SelectedPhysicians = referringPhysician;
gridData.SelectedCpt = cpt;
gridData.SelectedSpeciality = speciality;
gridData.PageSize = pageSize;
gridData.RowArea = rowArea;
gridData.IsVolume = isVolume;
gridData.page = 1;
gridData.total = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(ds.Tables[1].Rows[0][0]) / Convert.ToDouble(pageSize)));
gridData.records = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
gridData.col = sbcol.ToString();
gridData.colModel = sbcolModel.ToString();
gridData.rows = sbjsonRows.ToString().Trim();
gridData.order = order;
gridData.orderBy = orderBy;
gridData.direction = direction;
gridData.orderBySummary = orderBySummary;
gridData.orderBySummaryCol = OrderBySummaryCol;
gridData.ShowSubTotalForAllGroup = ShowSubTotalForAllGroup;
//Temporary Solution for getting the practice name for the corresponding practice
//var reader = SqlHelper.ExecuteReader(sqlConnectionString, CommandType.Text, "select practicename from practice where practiceid="+practice);
SqlConnection con = new SqlConnection(sqlConnectionString);
SqlCommand cmd = new SqlCommand();
Object returnValue;
cmd.CommandText = "select practicename from practice where practiceid="+practice;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
returnValue = cmd.ExecuteScalar();
con.Close();
gridData.SelectedPracticeName = returnValue.ToString();
return gridData;
}
catch (Exception ex)
{
Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(ex));
throw;
}
}
When you do
gd = HttpContext.Current.Session["SalesUserSession"] as GridData;
gd is an Object reference to HttpContext.Current.Session["SalesUserSession"]
that's why your session is impacted by your modifications.
this topic may help you achieve what you want :
Deep cloning objects
With ADO.net, if I want to retrieve the ID from combobox I just do such like this :
int idToGet = int.parse(tbCategory.SelectedValue.ToString());
Then done,
But when I bind the combobox with EF, it will show error Input string was not in a correct format. So the current value show { id = 7, category = TESTING } and not as usual.
Here a my code snippet :
public void loadCategory()
{
tbCategory.DataSource = null;
var listCategoryObj = new malsic_inventoryEntities();
var query = from cat in listCategoryObj.Category
//join cat in listItmObj.Category on n.id_category equals cat.id
select new { cat.id,cat.category };
if (query.Count() > 0)
{
tbCategory.DataSource = query.ToList();
tbCategory.DisplayMember = "category";
tbCategory.ValueMember = "id";
tbCategory.Invalidate();
}
else
{
tbSubCategory.Enabled = false;
}
}
public void loadSubcategory()
{
tbSubCategory.DataSource = null;
int id_category_current = int.Parse(tbCategory.SelectedItem.Value.ToString());
var listSubCategoryObj = new malsic_inventoryEntities();
var query = from SubCat in listSubCategoryObj.SubCategories
where SubCat.id_category == id_category_current
select new { SubCat.id, SubCat.subcategory };
if (query.Count() > 0)
{
groupBox1.Enabled = true;
tbSubCategory.DataSource = query.ToList();
tbSubCategory.DisplayMember = "subcategory";
tbSubCategory.ValueMember = "id";
tbSubCategory.Invalidate();
}
else
{
groupBox1.Enabled = false;
}
}
I do something wrong?
I don't think your problem is anything to with ADO.NET or Entity Framework. I think your problem is on the line with int.Parse. Try setting id_category_current this way instead of how you do it now:
int id_category_current;
if(!int.TryParse(tbCategory.SelectedItem.Value.ToString(), out id_category_current))
{
groupBox1.Enabled = false;
return;
}