Updating values in gridview is not working - c#

There is a row in gridview in which there is a column name as POA_NO whose value is 899.
But I am deleting that value and updating it as blank. But still it is getting updated as 899 only.
Here is my code
protected void GrdDetail_UpdateCommand(object sender, GridRecordEventArgs e)
{
if (Session["ViewInfo"] != null)
{
dtViewInfo = (DataTable)Session["ViewInfo"];
}
else
{
return;
}
DataRow[] drViewInfo = dtViewInfo.Select("SR_NO = " + e.Record["SR_NO"]);
if (e.Record["TYPE"] != "")
{
drViewInfo[0]["TYPE"] = e.Record["TYPE"];
}
else
{
drViewInfo[0]["TYPE"] = "NULL";
}
if (e.Record["REF_NO"] != "")
{
drViewInfo[0]["REF_NO"] = e.Record["REF_NO"];
}
if (e.Record["REF_DATE"] != "")
{
drViewInfo[0]["REF_DATE"] = e.Record["REF_DATE"];
}
if (e.Record["POA_NO"] != "")
{
drViewInfo[0]["POA_NO"] = e.Record["POA_NO"];
}
if (e.Record["POA_DATE"] != "")
{
drViewInfo[0]["POA_DATE"] = e.Record["POA_DATE"];
}
if (e.Record["POA_NAME"] != "")
{
drViewInfo[0]["POA_NAME"] = e.Record["POA_NAME"];
}
if (e.Record["ATTACHMENT"] != "")
{
drViewInfo[0]["ATTACHMENT"] = e.Record["ATTACHMENT"];
}
GrdDetail.DataSource = dtViewInfo;
GrdDetail.DataBind();
AddToViewState("GridViewInfo");
}
EDIT
Page load code
dtViewInfo = CF.ExecuteDT("select sr_no, type, ref_no, to_char (ref_date,'dd/MM/yyyy') ref_date, POA_NO , to_char (POA_DATE, 'dd/MM/yyyy') POA_DATE, POA_NAME, attachment from xxcus.XXACL_PN_VIEW_DATA_INFO " +
"where mkey = '" + StrMkey + "' order by sr_no");
GrdDetail.DataSource = dtViewInfo;
GrdDetail.DataBind();
AddToViewState("GridViewInfo");

Related

How to limit the amount of parameters for concatenatenation?

The idea of the program is to concatenate different parameters and put it all inside another parameter. How to let the end user decide if he wants to concatenate 2 or 3 parameters. Right now it is like if you don't put in 3 parameters it won't work. Nothing I came up with works.
namespace CombineParametersWinForm
{
public partial class Form1 : System.Windows.Forms.Form
{
//Class variable
Document revitDoc { get; set; }
public Form1(Document doc)
{
InitializeComponent();
this.revitDoc = doc;
//Create a list of the parameters you want your user to choose from
List<string> stringParameters = new List<string>
{
"Weight",
"Angle",
"Manufacturer"
};
//Add list to comboboxes on form
foreach (string parameterName in stringParameters)
{
comboBox1.Items.Insert(0, parameterName);
comboBox2.Items.Insert(0, parameterName);
comboBox3.Items.Insert(0, parameterName);
}
}
private void button1_Click(object sender, EventArgs e)
{
FilteredElementCollector collector = new FilteredElementCollector(revitDoc);
ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_PipeFitting);
//Applying Filter
IList<Element> ducts = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
foreach (Element duct in ducts)
{
//Get Parameter values
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsValueString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsValueString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsValueString();
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
//do not need .ToString() when setting parameter
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}
Ideas. First is pretty long one.
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsValueString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsValueString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsValueString();
if (parameterValue1 != "" || parameterValue1 != null)
{
parameterValue1 = parameterValue11;
}
if (parameterValue2 != "" || parameterValue2 != null)
{
parameterValue1 = parameterValue22;
}
if (parameterValue3 != "" || parameterValue3 != null)
{
parameterValue3 = parameterValue33;
}
if (parameterValue1 == "" || parameterValue1 == null)
{
parameterValue11 = "";
}
if (parameterValue2 == "" || parameterValue2 == null)
{
parameterValue22 = "";
}
if (parameterValue3 == "" || parameterValue3 == null)
{
parameterValue33 = "";
}
string newValue = parameterValue1 + "-" + parameterValue2 + "-" + parameterValue3;
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}
}
}
}
}
Second is a short one but still doesn't work
string parameterValue1 = duct.LookupParameter(comboBox1.Text).AsValueString();
string parameterValue2 = duct.LookupParameter(comboBox2.Text).AsValueString();
string parameterValue3 = duct.LookupParameter(comboBox3.Text).AsValueString();
List<string> listParam = new List<string> { parameterValue1, parameterValue2, parameterValue3 };
foreach (string s in listParam)
{
if (s != "" /*&& s != null*/)
{
List<string> listParamNotNull = new List<string> { s };
string newValue = String.Join(" ,", listParamNotNull);
using (Transaction t = new Transaction(revitDoc, "Set Parameter name"))
{
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}
You are creating three separate Lists and wanting to do something against all of them combined, but actually doing against each of them individually, overwriting as you go.
Please take a closer look at your nested logic.
Something like this is likely more appropriate:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string parameterValue1 = "Value1";
string parameterValue2 = ""; // purposefully providing an empty value
string parameterValue3 = "Value3";
var listParamIn = new List<string> { parameterValue1, parameterValue2, parameterValue3 };
var listParamOut = new List<string>();
foreach (string s in listParamIn){
if (string.IsNullOrEmpty(s))
continue;
listParamOut.Add(s);
}
string newValue = String.Join(", ", listParamOut);
Console.WriteLine(newValue);
/* continue with your transaction
using (Transaction t = new Transaction(revitDoc, "Set Parameter name")){
t.Start();
duct.LookupParameter("New").Set(newValue);
t.Commit();
}
*/
}
}
Output:
Value1, Value3
See:
https://dotnetfiddle.net/mXdL5F

how to ignore error records while updating the entries when error inner exception for details

How can I ignore writing of records giving error while updating the entities.
ERROR DISPLAY
private void btn_salary_Click(object sender, EventArgs e)
{
if (sg.HasRows(lib.tbl_pay) == true && chkShowOnly.Checked == false)
{
lib.ShowMessage(lib.tbl_pay + " has data can not import");
return;
}
sql = "SELECT * FROM PAY WHERE BankAc IS NOT null";
q1 = new DBFHelper(txt_olddir.Text).FillDataTable(sql);
dataGridView1.DataSource = q1;
if (chkShowOnly.Checked == true) return;
DateTime xdate = sg.ServerDate;
for (int x = 0; x < q1.Rows.Count; x++)
{
PAY q11 = new PAY
{
BANKAC = sg.AsString(q1.Rows[x]["BankAc"]),
MDATE = sg.AsDate(q1.Rows[x]["MDATE"].ToString()),
BYEAR = sg.AsDate(q1.Rows[x]["MDATE"].ToString()).Year,
BMONTH = sg.AsDate(q1.Rows[x]["MDATE"].ToString()).Month,
PERPAY = q1.AsDecimal("PERPAY", x),
BASIC = q1.AsDecimal("PERPAY", x),
DARATE = q1.AsDecimal("DA", x),
NEWDA = q1.AsDecimal("NEWDA",x),
ADNDA = q1.AsDecimal ("ADNDA",x),
HRA = q1.AsDecimal ("HRA",x),
ENTREL = q1.AsDecimal("ENTREL",x),
EXTRA = q1.AsDecimal("EXTRA",x),
INSKNP = q1.AsDecimal("INSGKP",x),
MEDI = q1.AsDecimal("MEDI",x),
RD = q1.AsDecimal("RD",x),
GPF = q1.AsDecimal("GPF",x),
GPFLOAN= q1.AsDecimal("GPFLOAN",x),
CPF = q1.AsDecimal("CPF",x),
CPFLOAN = q1.AsDecimal("CPFLOAN",x),
LICPRE = q1.AsDecimal("LICPRE",x),
LICLOAN = q1.AsDecimal("LICLOAN",x),
ITAX = q1.AsDecimal("ITAX",x),
JSBLOAN = q1.AsDecimal("JSBLOAN",x),
NSBLOAN = q1.AsDecimal("NSBLOAN",x),
STEMP = q1.AsDecimal("STEMP",x),
PROFUND = q1.AsDecimal("PROFUND",x),
TYPE_ATX = q1.AsString("TYPE",x),
GRADE = q1.AsString("GRADE",x),
TFUND = q1.AsDecimal("TFUND",x),
GFUND = q1.AsDecimal("GFUND",x),
OBCLOAN = q1.AsDecimal("OBCLOAN",x),
OTH1_LOAN = q1.AsDecimal("OTH1_LOAN",x),
OTH2_LOAN = q1.AsDecimal("OTH2_LOAN",x),
BSTGBANK = q1.AsDecimal("BSTGBANK",x),
EARNING = q1.AsDecimal("EARNING",x),
TOTDED = q1.AsDecimal("TOTDED",x),
NETPAY = q1.AsDecimal("NETPAY",x),
CITYALW = q1.AsDecimal("CITYALW",x),
user_code = lib.user_code,
modi_dt = xdate
};
g1.PAYs.Add(q11);
lbl_counter.Text = x.ToString() + " Records Inserted";
Application.DoEvents();
}
try
{
g1.SaveChanges();
}
catch (Exception ex)
{
string emsg = ex.Message;
if (ex.InnerException != null)
{
emsg = emsg + ex.InnerException.Message;
}
if (ex.InnerException.InnerException != null)
{
emsg = emsg + ex.InnerException.InnerException.Message;
}
if (ex.InnerException.InnerException.InnerException != null)
{
emsg = emsg + ex.InnerException.InnerException.InnerException.Message;
}
lib.ShowMessage(emsg);
}
lib.ShowMessage("Done..");
}

how can I add or update values with select count (*) and parameters SQL table and c#?

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.

Error in displaying the List of programs from database

Here i am trying to show the list of programs from database in my list.cshtml. I am not able to get the list of programs.
Suggest me if there is any wrong in code. I am facing issue in cacheUtilities as ArgumentNullException. someone help me with the code issue to get the list of programs from database.
Controller Code
[HttpGet]
[Authorize(Roles = "Affiliate")]
public ActionResult GetTrainingPrograms(int? affiliateId, string searchStr, bool? active, string sort, int? start, int? limit)
{
int affId = UserData.AffiliateID;
if (affiliateId != null && affiliateId.Value > 0)
{
affId = affiliateId.Value;
}
string searchStrLower = string.Empty;
string queryStr = String.Concat(affId);
// The start point in the list of Training Programs
if (start != null)
{
queryStr = String.Concat(queryStr, "-", start.Value);
}
// To find Active or Inactive at the Current Time
if (active != null)
{
queryStr = String.Concat(queryStr, "-", active);
}
// Sort the List of Data
if (sort == null)
{
sort = "trainingProgramName";
}
queryStr = String.Concat(queryStr, "-", sort);
// limit on the page to Display
if (limit != null)
{
queryStr = String.Concat(queryStr, "-", limit.Value);
}
//The keywords used to find a Training Program
if (!string.IsNullOrEmpty(searchStr))
{
searchStrLower = searchStr.ToLower();
queryStr = String.Concat(queryStr, "-", searchStrLower);
}
logger.Debug("trainingProgramListKey: " + queryStr);
TrainingProgramList reloadData = CacheUtilities.Instance.GetTrainingProgramList(affiliateId);
logger.Debug("reloadData: " + reloadData + ", affId: " + affId + ", queryStr: " + queryStr);
string trainingProgramCacheKey = CbConstants.TrainingProgramCacheKey + queryStr;
TrainingProgramList trainingProgramList = null;
int totalCount = 0;
// Checks the List is null or not to Display
if (trainingProgramList != null)
{
logger.Debug("Cache miss for TrainingProgram list: " + trainingProgramCacheKey);
trainingProgramList = new TrainingProgramList();
trainingProgramList.AffiliateID = affId;
totalCount = TrainingProgramRepository.Instance.GetTrainingProgramsCount(affId, searchStrLower, active);
trainingProgramList.Entries = TrainingProgramRepository.Instance.GetTrainingPrograms(affId, searchStrLower, active, sort, start, limit);
HttpRuntime.Cache.Insert(trainingProgramCacheKey, trainingProgramList, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationOneDay);
}
CbJsonResponse response = new CbJsonResponse();
response.Data.Add(trainingProgramList);
response.Status = "success";
response.Meta.Add("total", Convert.ToString(totalCount));
return Json(response, "application/json", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
}
}
Repository Code:
public List<TrainingProgramListEntry> GetTrainingPrograms(int affiliateId, string searchStr, bool? active, string sort, int? start, int? limit)
{
using (var ctx = new CrossfitPortalEntities())
{
ctx.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
// Don't need proxies when explicitly loading.
ctx.Configuration.ProxyCreationEnabled = false;
var query = ctx.TrainingPrograms.Where(m => m.AffiliateID == affiliateId);
//The keywords used to find a Training Program
if (!string.IsNullOrEmpty(searchStr))
{
query = query.Where(m => m.Name.ToLower().Contains(searchStr));
}
if (active != null)
{
}
// The property on which to sort this list.
if (sort != null)
{
switch (sort)
{
case "TrainingProgram Name":
query = query.OrderBy(m => m.Name);
break;
}
}
//The number of Training Programs to display on this page.
if (limit != null)
{
logger.Debug("TrainingProgram query limit: " + limit.Value);
}
var entries = query.Select(m => new TrainingProgramListEntry
{
Name = m.Name,
ColorCode = m.ColorCode,
// The start point in the list of Training Programs
}).Skip((start != null) ? start.Value : 0).Take((limit != null) ? limit.Value : 10).ToList();
return entries;
}
}
CacheUtilites Code:
public TrainingProgramList GetTrainingProgramList(int? affiliateID)
{
string trainingProgramCacheKey = CbConstants.TrainingProgramCacheKey + affiliateID;
TrainingProgramList trainingprogram = (TrainingProgramList)HttpRuntime.Cache[trainingProgramCacheKey];
if (trainingprogram != null)
{
logger.Debug("Cache hit for AffProfile Entity: " + trainingProgramCacheKey);
}
else
{
logger.Debug("Cache miss for AffProfile Entity: " + trainingProgramCacheKey);
trainingprogram = TrainingProgramRepository.Instance.GetTrainingPrograms(AffiliateID);
HttpRuntime.Cache.Insert(trainingProgramCacheKey, trainingprogram, null, Cache.NoAbsoluteExpiration, CbConstants.CacheSlidingExpirationTwoHours);
}
return trainingprogram;
}

The file * has been modified by SHAREPOINT\system

In the current scenario I am trying to copy a document set from one library to another, the thing is I cant use DocumentSet.Import because I only need the docset properties and not the contents.
The exception is thrown in the System.Update of this code.
private void CopyAgendaPointToRootSite(SPListItem agendaPointItem, string oldReasonReturned)
{
try
{
if (agendaPointItem != null)
{
SPWeb currentSite = agendaPointItem.ParentList.ParentWeb;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(currentSite.Site.RootWeb.Url))
{
using (SPWeb elevatedTargetWeb = site.OpenWeb())
{
SPList targetList = GetAgendaPointProposedTargetLibrary(agendaPointItem, elevatedTargetWeb);
SPDocumentLibrary targetDocumentLibrary = (SPDocumentLibrary)targetList;
SPContentTypeId targetCTId = targetList.ContentTypes.BestMatch(new SPContentTypeId(MeetingsCommon.Constants.CONTENTTYPES_AGENDAPOINTPROPOSED_ID));
DocumentSet documentSet = DocumentSet.GetDocumentSet(agendaPointItem.Folder);
if (documentSet != null)
{
string strAgendaPointTitle = agendaPointItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTTITLENL_NAME] +
" / " + agendaPointItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTTITLEFR_NAME];
SPListItemCollection colProposedItems = FindAgendaPointProposedItem((SPDocumentLibrary)targetList, documentSet.Item.Name);
if (colProposedItems.Count > 0)
throw new Exception(string.Format(HelperFunctions.GetResourceString(
MeetingsCommon.Constants.RESOURCES_FILE_NAME,
"Message_AgendaPointsEvents_ERROR_DocumentSetAlreadyExistsInRootSite2"), strAgendaPointTitle));
using (DisableItemEventScope scope = new DisableItemEventScope())
{
DocumentSet docSetCreated = DocumentSet.Create(targetList.RootFolder, agendaPointItem.Name, targetCTId, new Hashtable(), true);
SPListItem listItem = docSetCreated.Item;
foreach (SPField field in agendaPointItem.Fields)
{
if (!field.ReadOnlyField && field.InternalName != "Attachments" && field.InternalName != "TaxCatchAll")
{
if (agendaPointItem[field.Id] != null)
{
string targetFieldInternalName = field.InternalName;
if (listItem.Fields.ContainsField(field.InternalName))
{
listItem[targetFieldInternalName] = agendaPointItem[field.InternalName];
}
}
}
}
string reasonreturned = "---- <br/>Reason returned: " + currentSite.Title + " Rejected. " + "<br/> "
+ agendaPointItem.GetTaxonomyFieldValueByLanguage(site, MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISION_NAME, 1036) + "<br/> "
+ agendaPointItem.GetTaxonomyFieldValueByLanguage(site, MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISION_NAME, 1043) + "<br/> "
+ agendaPointItem.GetFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISIONCOMMENTSNL_NAME)
+ agendaPointItem.GetFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISIONCOMMENTSFR_NAME)
+ agendaPointItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTSREASONRETURNED_NAME] + "<br/>----";
SPFieldUrlValue value = new SPFieldUrlValue();
value.Description = currentSite.Title;
value.Url = currentSite.Url;
listItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTPOSTPONEDFROM_NAME] = value;
listItem[MeetingsCommon.Constants.FIELDS_MEETING_NAME] = null;
listItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTSTATUS_NAME] = null;
listItem[MeetingsCommon.Constants.FIELDS_AGENDAPOINTSREASONRETURNED_NAME] = reasonreturned;
//Clear the category and status field
listItem.ClearTaxonomyFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTSTATUS_NAME);
listItem.ClearTaxonomyFieldValue(MeetingsCommon.Constants.FIELDS_AGENDAPOINTDECISION_NAME);
listItem.SystemUpdate(false);
}
}
}
}
});
}
}
catch (Exception ex)
{
throw;
}
}
I fixed it doing the following
DocumentSet docSetCreated = DocumentSet.Create(targetList.RootFolder, agendaPointItem.Name, targetCTId, new Hashtable(), true);
int listItemId = docSetCreated.Item.ID;
SPListItem listItem = targetList.GetItemById(listItemId);
apparently after the documentset is created, I cant use the listitem of that object anymore, I need to get a new one

Categories