After trying to mix a fileupload and json data in postman i finally found a method where it is possible to send them both in the same request. Therefore, I have moved my json data to a Key in Postman, so that it becomes possible to send files as well using form-data (Picture below).
Within the value I have JSON data as following:
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"DamageDate":"2021-05-03",
"DamageKilometerreading":"213",
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":"1223",
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
The empty {} just contains more service types. Now when I send the request in Postman i get a 200 OK and when i debug i can see the following (sorry if the picture is blurry):
¨
However, my database does not get updated with these values. Here's the class for inserting data into the tables:
public async Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData)
{
bool CreateRequest = true;
int requestID = 0;
int claimID = 0;
//bool country = true;
//First Create the Request
foreach (Service item in model.Service)
{
//First Create the Request
if (CreateRequest)
{
var parameters = new DynamicParameters();
parameters.Add("WorkshopEmail", model.WorkshopEmail);
parameters.Add("WorkshopContactperson", model.WorkshopContactperson);
parameters.Add("WorkshopCellphone", model.WorkshopCellphone);
parameters.Add("DamageDate", model.DamageDate);
parameters.Add("LatestServiceDate", model.LatestServiceDate);
parameters.Add("LatestServiceKilometer", model.LatestServiceKilometer);
parameters.Add("DamageKilometerreading", model.DamageKilometerreading);
parameters.Add("CurrentKilometerreading", model.CurrentKilometerreading);
parameters.Add("CarOwnerDescription", model.CarOwnerDescription);
parameters.Add("WorkshopDiagnos", model.WorkshopDiagnos);
parameters.Add("AmountIncVat", model.AmountIncVat);
try
{
var requestIDenum = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[Request]
(WorkshopEmail,WorkshopContactperson,WorkshopCellphone,DamageDate,LatestServiceDate,
LatestServiceKilometer,DamageKilometerreading,CurrentKilometerreading,
CarOwnerDescription,WorkshopDiagnos,AmountIncVat)
VALUES
(#WorkshopEmail,#WorkshopContactperson,#WorkshopCellphone,#DamageDate,#LatestServiceDate,
#LatestServiceKilometer,#DamageKilometerreading,#CurrentKilometerreading,
#CarOwnerDescription,#WorkshopDiagnos,#AmountIncVat);SELECT SCOPE_IDENTITY();",parameters);
requestID = requestIDenum.First();
CreateRequest = false;
}
catch(Exception ex)
{
int hej = 0;
}
}
if (item.fileuploadresults != null)
{
foreach (FileUploadResult f in item.fileuploadresults)
{
var parameters = new DynamicParameters();
parameters.Add("file", f.filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO [dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
int FileMessageID = filemessage.First();
await _sqlconnection.QueryAsync<int>($#"INSERT INTO[dbo].[ClaimCrossOptionalFile]
(ClaimID,FileID)
VALUES
({claimID},{FileMessageID});");
}
}
return true;
//return list;
}
Controller:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
// if (!ModelState.IsValid)
// {
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
try
{
//await _request.AddRequest(request);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Interface:
Task<bool> AddRequest(Request model, List<IFormFile> file, [FromForm] string jsonData);
Sidenote: This is part of the code, as i've tried to keep it short, so perhaps some } or something is missing here, but there's no problem. If i should add the whole code i could perhaps send it in a link or something similar, as it would be a lot to upload here.
However, I do not now how to proceed with this issue at the moment. I've not worked with form-data much before, at least not with passing json as a value. Perhaps there's something I'm missing/have to do in the controller with the json data? I've tried looking for solutions but I've gotten stuck here. The only issue is that the database does not get updated.
Update, the model:
public class Work
{
//base for claim
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
public string id { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string quantity { get; set; } = "";
//service
public int rentreasonId { get; set; } = -1;
public int rentservicecartypeId { get; set; } = -1;
//tyres
public int tireserviceId { get; set; } = -1;
public IList<TireType> tireTypes { get; set; }
public IList<Labour> labours { get; set; }
public DateTime DateFrom{ get; set; } = DateTime.Parse("1753-01-01");
public DateTime DateTo { get; set; } = DateTime.Parse("1753-01-01");
//Insurance
public string totalAmount { get; set; }
public string requestInsuranceVatID { get; set; }
public string vat { get; set; } = "0.0";
public string totalExclVat { get; set; }="0.0";
public string totalIncVat { get; set; }="0.0";
}
public class Labour
{
public string title { get; set; } = "";
public string chargePerHour { get; set; } = "";
public string hours { get; set; } = "";
public string price { get; set; } = "";
}
public class TireType
{
public string quantity { get; set; } = "";
public string brand { get; set; } = "";
public string model { get; set; } = "";
public string pricePerUnit { get; set; } = "";
public string price { get; set; } = "";
public string tireTypeId { get; set; } = "";
public string widthID { get; set; } = "";
public string heightID { get; set; } = "";
public string diameterID { get; set; } = "";
}
public class Request
{
public string WorkshopEmail { get; set; } = "";
public string WorkshopContactperson { get; set; } = "";
public string WorkshopCellphone { get; set; } = "";
public int AmountIncVat { get; set; } = 0;
#region Claim
public DateTime DamageDate { get; set; } = DateTime.Parse("1753-01-01");
public DateTime LatestServiceDate { get; set; } = DateTime.Parse("1753-01-01");
public int LatestServiceKilometer { get; set; } = 0;
public int DamageKilometerreading { get; set; } = 0;
public int CurrentKilometerreading { get; set; } = 0;
public string CarOwnerDescription { get; set; } = "";
public string WorkshopDiagnos { get; set; } = "";
//public string OptionalMessage { get; set; } = "";
#endregion
public IList<Service> Service { get; set; }
}
public class TireTread
{
public string tireserviceId { get; set; } = "";
public string leftfront { get; set; } = "";
public string rightfront { get; set; } = "";
public string leftrear { get; set; } = "";
public string rightrear { get; set; } = "";
public string added1 { get; set; } = "";
public string added2 { get; set; } = "";
public string added3 { get; set; } = "";
public string added4 { get; set; } = "";
public string added5 { get; set; } = "";
}
public class TireMessage
{
public int tireserviceId { get; set; }
public string message { get; set; }
}
public class Service
{
// [JsonProperty("ServiceId")]
public string RequestTypeId { get; set; } = "";
public string CategoryId { get; set; } = "-1";
public string OptionalMessage { get; set; } = "";
public IList<Work> works { get; set; }
public IList<TireTread> treads { get; set; }
public IList<TireMessage> TireMessages { get; set; }
//filuppladdning
public IList<FileUploadResult> fileuploadresults { get; set; }
}
//filuppladdning
public class FileUploadResult
{
//public IFormFile files { get; set; }
public string filename { get; set; }
}
Firstly,the json format does not match the model structure.You need to pass json like this(Pay attention to DamageKilometerreading and LatestServiceKilometer,the type of them are int,so don't use ""):
{
"WorkshopEmail":"workshopemail",
"WorkshopContactperson":"workshopcontactperson",
"WorkshopCellphone":"workshopcellphone",
"DamageDate":"2021-05-03",
"DamageKilometerreading":213,
"LatestServiceDate":"2021-05-03",
"LatestServiceKilometer":1223,
"WorkshopDiagnos":"diagnos workshop",
"CarOwnerDescription":"carownerdescription",
"Service":[
{
"service":"Claim Airbag",
"RequestTypeId":"1",
"CategoryId":"25",
"works":[
{
"title":"arbete 1 airbag",
"chargePerHour":"11",
"hours":"12",
"price":"132.00",
"id":"13926"
},
{
"title":"arbete2 airbag",
"chargePerHour":"1",
"hours":"2",
"price":"2.00",
"id":"13927"
},
{
"title":"part1 airbag",
"pricePerUnit":"100",
"quantity":"1",
"price":"100.00",
"id":"13928"
},
{
"title":"part2 airbag",
"pricePerUnit":"100",
"quantity":"2",
"price":"200.00",
"id":"13929"
}
]
},
{},
{},
{},
{},
{}
]
}
Then try to add public string service { get; set; }="" inService model.
I found a solution, in case anyone else comes across this problem. I needed to modify the controller and add this code:
[HttpPost]
public async Task<IActionResult> AddRequest(List<IFormFile> file, [FromForm] string jsonData)
{
Request request = JsonConvert.DeserializeObject<Request>(jsonData);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
await _request.AddRequest(request, file, jsonData);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok();
}
Basically adding request (that I deserialize in the begining of the method), and adding the file, and jsonData in an await request, solved the problem. As for the fileuploading, I needed to modify that method as well, to get the filename into the database:
if (file != null)
{
foreach (IFormFile f in file)
{
string filename = Path.GetFileName(f.FileName);
var parameters = new DynamicParameters();
parameters.Add("file", filename);
var filemessage = await _sqlconnection.QueryAsync<int>($#"INSERT INTO
[dbo].[OptionalFile] ([FileName])
VALUES (#file); SELECT SCOPE_IDENTITY();", parameters);
}
}
Changing these to made it possible to send a request containg both the json key value, and multiple files, in the same request.
List object inside list object in crystal report using webApi.
private RailCommerceDBEntities db = new RailCommerceDBEntities();
[HttpGet]
public HttpResponseMessage ExportReport()//ParameterReport preport
{
string format = string.Empty;
//format = preport.Format;
format = ".pdf";
List<TaskReports> model = new List<TaskReports>();
//if (preport.Issue == null)
//{
// preport.Issue = "";
//}
//if (preport.OfficerResponsible == null)
//{
// preport.OfficerResponsible = "";
//}
// var data = db.spsantoshTaskTrackingAnupTe(preport.TaskID, preport.Issue, preport.Designation, preport.TaskCoordinator, preport.OfficerResponsible, preport.FollowedBy, preport.DecisionFromDate, preport.DecisionToDate, preport.Priority, preport.Category, preport.DeadlineFromDate, preport.DeadlineToDate, preport.Attachment).ToList();
// var data = db.spsantosh(null, "", null, null, "", null, null, null, null, null, null, null, null).ToList();
var data = db.spCrystalReport(null, "", null, null, "", null, null, null, null, null, null, null, null).ToList();
string[] arr = new string[100];
List<OfficerRemark> myCollection = new List<OfficerRemark>();
//List<FinalList> lst = new List<FinalList>();
//dynamic Values=null;
var rd = new ReportDocument();
int counter = 0;
foreach (var details in data)
{
counter = counter + 1;
TaskReports obj = new TaskReports();
obj.SNO = counter;
obj.TaskID = details.TaskID;
var OfficeID = details.OfficerID.Split(',');
foreach (var item in OfficeID)
{
if (item != "null")
{
var item1 = Convert.ToInt32(item);
var Values = db.sp_RemarkBasedOnOfficerIDs(details.TaskID, item1).ToList();
foreach (var itemOff in Values)
{
OfficerRemark objofficer = new OfficerRemark();
objofficer.TaskID = Convert.ToInt32(itemOff.TaskID);
objofficer.IsRemarkUpdate = itemOff.IsRemarkUpdate;
objofficer.Remark = itemOff.Remark;
objofficer.RemarkUpdateDate = Convert.ToString(itemOff.RemarkUpdateDate);
objofficer.RemarkUpdatedBy = Convert.ToInt32(itemOff.RemarkUpdatedBy);
objofficer.UserName = itemOff.UserName;
myCollection.Add(objofficer);
}
// myCollection.Add(Values);
}
}
obj.Issue = details.Issue;
if (details.ActionJS != null)
{
obj.ActionJs = details.ActionJS;
}
if (details.ActionUpdateDate != null)
{
obj.ActionTCDateHistory = Convert.ToString(details.ActionUpdateDate);
}
//obj.ActionJs = details.ActionJs;
obj.FollowedByName = details.FollowedByName;
obj.GroupByName = details.GroupByName;
obj.AllDeadline = details.AllDeadline;
if (details.AttachFileIDs != null)
{
//obj.Counter = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("/UserImage/attachment.png"));
}
obj.IsAJSUpdate = details.IsActionJSUpdate;
obj.IsRemarkUpdate = details.IsRemarkUpdate;
foreach (var item in myCollection)
{
if (item.TaskID == obj.TaskID)
{
obj.AditionalComments = new List<ActionTestOne>();
obj.ActionOC = new List<ActionTestOne>();
obj.RemarkOCDateHistory = new List<ActionTestOne>();
ActionTestOne ac = new ActionTestOne();
//ActionOCOne aco = new ActionOCOne();
// ActionUpdate ad = new ActionUpdate();
ac.ActionOC = item.UserName;
ac.AditionalComment = item.Remark;
ac.RemarkUpdateDate = item.RemarkUpdateDate;
obj.AditionalComments.Add(ac);
obj.ActionOC.Add(ac);
obj.RemarkOCDateHistory.Add(ac);
}
}
obj.DateOFDecision = Convert.ToString(details.DateOFDecision);
obj.OfficerResponsible = details.OfficerResponsible;
obj.PriorityName = details.PriorityName;
obj.Statuss = Convert.ToInt32(details.Statuss);
obj.StatusTpye = details.StatusTpye + '(' + Convert.ToString(obj.Statuss) + ')';
obj.TaskCoordinator = details.TaskCoordinator;
DateTime objcu = DateTime.Now;
obj.Counter = Convert.ToString(objcu);
model.Add(obj);
}
//rd.Load(Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Report/TaskTrReport.rpt")));
rd.Load(Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Report/TaskTrackReport.rpt")));
ConnectionInfo connectInfo = new ConnectionInfo()
{
ServerName = "103.14.97.209",
DatabaseName = "RailCommerceDB",
UserID = "UP3M5m6Tb4",
Password = "UP3M5m6Tb4"
};
rd.SetDatabaseLogon("UP3M5m6Tb4", "UP3M5m6Tb4");
//System.Web.UI.WebControls.Table tbl = new System.Web.UI.WebControls.Table
foreach (Table tbl in rd.Database.Tables)
{
tbl.LogOnInfo.ConnectionInfo = connectInfo;
tbl.ApplyLogOnInfo(tbl.LogOnInfo);
}
**rd.SetDataSource(model);**
var stream = rd.ExportToStream(ExportFormatType.PortableDocFormat);
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(stream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "CIMDashboard_Report" + format + "";
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return httpResponseMessage;
}
--------------------------------
public class TaskReports
{
public int SrNo { get; set; }
public int SNO { get; set; }
public int TaskID { get; set; }
public string ActionTaken { get; set; }
public string Issue { get; set; }
public int ActionUpdatedBy { get; set; }
public string ActionUpdateDate { get; set; }
public string OfficerResponsible { get; set; }
public string DateOFDecision { get; set; }
public string AttachFileIDs { get; set; }
public string TaskCoordinator { get; set; }
public string PriorityName { get; set; }
public int Statuss { get; set; }
public string StatusTpye { get; set; }
public string AllDeadline { get; set; }
//
public string ActionTC { get; set; }
public string ActionTCDateH { get; set; }
//public List<string> ActionOC { get; set; }
public List<ActionTestOne> ActionOC { get; set; }
public string RemarkOCDH { get; set; }
//Additional
public string IsAJSUpdate { get; set; }
public string IsRemarkUpdate { get; set; }
public string Remark { get; set; }
public int TaskOwnerID { get; set; }
public string FollowedByName { get; set; }
public string GroupByName { get; set; }
public int RemarkUBy { get; set; }
public string ActionJs { get; set; }
public string CurrentDateTime { get; set; }
public List<ActionTestOne> AditionalComments { get; set; }
public string Counter { get; set; }
public List<ActionTestOne> RemarkOCDateHistory { get; set; }
public string ActionTCDateHistory { get; set; }
//public string AditionalComments { get; set; }
//public string ActionOC { get; set; }
//public string RemarkUpdateDate { get; set; }
//public string RemarkOCDateHistory { get; set; }
}
public class ActionTestOne
{
public string AditionalComment { get; set; }
public string ActionOC { get; set; }
public string RemarkUpdateDate { get; set; }
}
--------------------------------------------------
public class OfficerRemark
{
public int TaskID { get; set; }
public int RemarkUpdatedBy { get; set; }
public string Remark { get; set; }
public string RemarkUpdateDate { get; set; }
public string IsRemarkUpdate { get; set; }
public string UserName { get; set; }
}**
list object inside list object data is not showing in crystal report in web api.Please help what i missing in crystal report.
my list object is model and inside list object name is AdditionalsComments and ActionOC but data is not showing in crystal report.
Crystal supports only one level of subreport embedding.
A report can contain a subreport. But a subreport cannot contain a subreport.
I have class which I am implementing the proptery changed event but for some reason my listview will not update the data until I close the app and re launch it.
public BindingList<SalesOrders> GetSalesOrders()
{
BindingList<SalesOrders> _salesOrdersList = new BindingList<SalesOrders>();
try
{
string sageDsn = ConfigurationManager.AppSettings["SageDSN"];
string sageUsername = ConfigurationManager.AppSettings["SageUsername"];
string sagePassword = ConfigurationManager.AppSettings["SagePassword"];
//using (var connection = new OdbcConnection("DSN=SageLine50v24;Uid=Manager;Pwd=;"))
using (var connection = new OdbcConnection(String.Format("DSN={0};Uid={1};Pwd={2};", sageDsn, sageUsername, sagePassword)))
{
connection.Open();
//string sql = string.Format(getInvoiceSql, customerCode, DateTime.Today.AddMonths(-1).ToString("yyyy-MM-dd"));
string fromD = dtpFrom.Value.ToString("yyyy-MM-dd");
string toD = dtpTo.Value.ToString("yyyy-MM-dd");
String SQL = string.Format("SELECT 'ORDER_NUMBER', 'ORDER_OR_QUOTE', 'ANALYSIS_1','ACCOUNT_REF','ORDER_DATE','NAME', 'COURIER_NUMBER','COURIER_NAME','CUST_TEL_NUMBER' ,'DESPATCH_DATE','ACCOUNT_REF', 'DEL_NAME', 'DEL_ADDRESS_1', 'DEL_ADDRESS_2', 'DEL_ADDRESS_3', 'DEL_ADDRESS_4', 'DEL_ADDRESS_5', 'INVOICE_NUMBER','INVOICE_NUMBER_NUMERIC', 'CONTACT_NAME','CONSIGNMENT', 'NOTES_1', 'ITEMS_NET' ,'ITEMS_GROSS','QUOTE_STATUS' FROM SALES_ORDER WHERE ORDER_DATE >='{0}' and ORDER_DATE <='{1}'", fromD, toD);
using (var command = new OdbcCommand(SQL, connection))
{
backgroundWorker1.ReportProgress(15);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
backgroundWorker1.ReportProgress(35);
counter++;
var salesOrders = new SalesOrders();
if ((reader["ORDER_NUMBER"] != ""))
{
string orderNumber = Convert.ToString(reader["ORDER_NUMBER"]);
salesOrders.ACCOUNT_REF = Convert.ToString(reader["ACCOUNT_REF"]);
salesOrders.RecordIdentifier = "SHN";
salesOrders.ShipmmentId = Convert.ToString(reader["ORDER_NUMBER"]);
salesOrders.OrderDate = Convert.ToDateTime(reader["ORDER_DATE"]);
salesOrders.OrderNumber = Convert.ToString(reader["ORDER_NUMBER"]);
salesOrders.Company = "hackett";
salesOrders.Carrier = Convert.ToString(reader["COURIER_NUMBER"]);
salesOrders.CarrierService = Convert.ToString(reader["COURIER_NAME"]);
salesOrders.CustomerName = Convert.ToString(reader["NAME"]);
salesOrders.ShipToAddress1 = Convert.ToString(reader["DEL_ADDRESS_1"]);
salesOrders.ShipToAddress2 = Convert.ToString(reader["DEL_ADDRESS_2"]);
salesOrders.ShipToAddress3 = Convert.ToString(reader["DEL_ADDRESS_3"]);
salesOrders.ShipToAddress4 = Convert.ToString(reader["DEL_ADDRESS_4"]);
salesOrders.ShipToAddress5 = Convert.ToString(reader["DEL_ADDRESS_5"]);
salesOrders.ShiptoAttention = Convert.ToString(reader["DEL_NAME"]);
salesOrders.ShiptoPhoneNo = Convert.ToString(reader["CUST_TEL_NUMBER"]);
salesOrders.Country = Convert.ToString(reader["ANALYSIS_1"]);
salesOrders.ShiptoEmail = "";
salesOrders.MakeAddressDefault = "Y";
salesOrders.ExporteDateTime = GetExportedDate(orderNumber);
bool isProcessed = hasbeenProcessed(orderNumber);
if (isProcessed == true)
salesOrders.Exported = true;
_salesOrdersList.Add(salesOrders);
}
backgroundWorker1.ReportProgress(80);
}
}
}
}
backgroundWorker1.ReportProgress(100);
}
catch (Exception ex)
{
}
return _salesOrdersList;
}
}
backgroundWorker1.ReportProgress(100);
}
catch (Exception ex)
{
}
return _salesOrdersList;
}
In my background worker i am creating the list here
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var listOrders = new List<SalesOrders>();
listOrders = GetSalesOrders().OrderByDescending(o => o.OrderDate).ToList();
var listBindingOrders = new BindingList<SalesOrders>(listOrders);
SalesOrders = listBindingOrders;
}
This is my constructor which I am binding the above.
public BindingList<SalesOrders> SalesOrders = new BindingList<BusinessObjects.SalesOrders>();
Here is my class as to which I am using the notifcation changed proprerty on the exported flag which is being changed but it only updates when I close the application.
public class SalesOrders : INotifyPropertyChanged
{
public bool selected { get; set; }
public string ORDER_OR_QUOTE { get; set; }
public string OrderNumber { get; set; }
public string ACCOUNT_REF { get; set; }
public string RecordIdentifier { get; set; }
public DateTime OrderDate { get; set; }
public string ShipmmentId { get; set; }
public string Company { get; set; }
public string Carrier { get; set; }
public string CarrierService { get; set; }
public string Customer { get; set; }
public string CustomerName { get; set; }
public string ShiptoName { get; set; }
public string ShipToAddress1 { get; set; }
public string ShipToAddress2 { get; set; }
public string ShipToAddress3 { get; set; }
public string ShipToAddress4 { get; set; }
public string ShipToAddress5 { get; set;
}
public string ShiptoAttention { get; set; }
public string ShiptoPhoneNo { get; set; }
public string ShiptoEmail { get; set; }
public string County { get; set; }
public string MakeAddressDefault { get; set; }
public string Address
{
get
{
var sb = new StringBuilder();
sb.Append(ShipToAddress1);
sb.Append(ShipToAddress2);
sb.Append(ShipToAddress3);
return sb.ToString();
}
}
private bool ExportedValue = false;
public bool Exported
{
get { return this.ExportedValue; }
set
{
if (value != this.ExportedValue)
{
this.ExportedValue = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// The cons
public DateTime ExporteDateTime { get; set; }
public String Country { get; set; }
}
I thought it would be important to show my binding event here.
// <summary>
/// Bind the list view to the sales order collection
/// </summary>
/// <param name="_salesOrders"></param>
private void BindListView(BindingList<SalesOrders> _salesOrders)
{
invoiceListView.Items.Clear();
foreach (SalesOrders _pur in _salesOrders)
{
invoiceListView.Items.Add(CreateListViewItem(_pur));
}
foreach (ListViewItem lvw in invoiceListView.Items)
{
Boolean hasExported = Convert.ToBoolean(lvw.SubItems[8].Text);
if (hasExported == true)
{
lvw.BackColor = Color.Wheat;
}
}
}
I hope someone can help me out this is driving me nuts at the minute everything else is working but data refresh.
Have you made sure that you have a BindingList that is associated with your ListView using listView1.ItemsSource = bindingList, and then sticking to modifying the actual BindingList instead of the ListView? (Eg. not using listView1.Items.Add, but simply adding to the listViews binding collection)
Have you tried to use the .refresh() method everytime
:)
I have a datagridview and I fill it by List (I get data from 2 text files), but when I tried to click on a column header (I tried with all columns headers), I can't sort my datagridview data. This is my code:
public class Data1
{
public string Campionato { get; set; }
public string Data { get; set; }
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public int HSHT { get; set; }
public int ASHT { get; set; }
public int HSSH { get; set; }
public int ASSH { get; set; }
}
public class Data2
{
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public string HODD { get; set; }
public string XODD { get; set; }
public string AODD { get; set; } //no name in sample
public string Data { get; set; }
public string RisFin { get; set; } //no name in sample
public string Over05SH { get; set; }
public string Over05HT { get; set; }
public string Over15HT { get; set; }
public string Over05FT { get; set; }
public string Over15FT { get; set; }
public string Over25FT { get; set; }
public string Over35FT { get; set; }
public string Over45FT { get; set; }
}
public class CombinedData
{
public string Campionato { get; set; }
public string Data { get; set; }
public string Home { get; set; }
public string Away { get; set; }
public int HSFT { get; set; }
public int ASFT { get; set; }
public int HSHT { get; set; }
public int ASHT { get; set; }
public int HSSH { get; set; }
public int ASSH { get; set; }
public string HODD { get; set; }
public string XODD { get; set; }
public string AODD { get; set; } //some name
public string RisFin { get; set; } //no name in sample
public string Over05SH { get; set; }
public string Over05HT { get; set; }
public string Over15HT { get; set; }
public string Over05FT { get; set; }
public string Over15FT { get; set; }
public string Over25FT { get; set; }
public string Over35FT { get; set; }
public string Over45FT { get; set; }
}
var data1 = File.ReadAllLines("read" + campionatoselezTxt.Text + "stats.txt").ToList();
var data2 = File.ReadAllLines("read" + campionatoselezTxt.Text + "bex.txt").ToList();
var dataList1 = new List<Data1>();
foreach (var data in data1)
{
var columns = data.Split(';');
dataList1.Add(new Data1
{
Campionato = columns[0],
Data = columns[1],
Home = columns[2],
Away = columns[3],
HSFT = int.Parse(columns[4]),
ASFT = int.Parse(columns[5]),
HSHT = int.Parse(columns[6]),
ASHT = int.Parse(columns[7]),
HSSH = int.Parse(columns[8]),
ASSH = int.Parse(columns[9])
//other int properties
});
}
var dataList2 = new List<Data2>();
foreach (var data in data2)
{
var columns = data.Split(';');
dataList2.Add(new Data2
{
Home = columns[0],
Away = columns[1],
HODD = columns[4],
XODD = columns[5],
AODD = columns[6],
});
}
var combinedDataList = from d1 in dataList1
//join d2 in dataList2 on d1.Home equals d2.Home
join d2 in dataList2 on new { d1.Home, d1.Away } equals new { d2.Home, d2.Away }
select new CombinedData
{
Campionato = d1.Campionato,
Data = d1.Data,
Home = d2.Home,
Away = d2.Away,
HSFT = d1.HSFT,
ASFT = d1.ASFT,
HSHT = d1.HSHT,
ASHT = d1.ASHT,
HSSH = d1.HSSH,
ASSH = d1.ASSH,
HODD = d2.HODD,
XODD = d2.XODD,
AODD = d2.AODD,
RisFin = d2.RisFin,
Over05SH = d2.Over05SH
}; //map all properties
finabexDgv.DataSource = combinedDataList.ToList();
finabexDgv.AllowUserToOrderColumns = true;
I'd like to have a possibility to sort by clicking columns headers.
I need your advices, please :)
Happy Sunday!
On your desing view, search the "ColumnHeaderMouseClick" and double click on the empty field.
on the new function, apply some code like this:
dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dgv.Columns[e.ColumnIndex].SortMode != DataGridViewColumnSortMode.NotSortable)
{
if (e.ColumnIndex == newSortColumn )
{
if (newColumnDirection == ListSortDirection.Ascending)
newColumnDirection = ListSortDirection.Descending;
else
newColumnDirection = ListSortDirection.Ascending;
}
newSortColumn = e.ColumnIndex;
switch (newColumnDirection)
{
case ListSortDirection.Ascending:
dgv.Sort(dgv.Columns[newSortColumn], ListSortDirection.Ascending);
break;
case ListSortDirection.Descending:
dgv.Sort(dgv.Columns[newSortColumn], ListSortDirection.Descending);
break;
}
}
}
and at the top of the class, add two private variables:
int newSortColumn;
ListSortDirection newColumnDirection = ListSortDirection.Ascending;
This will work if you don't have anything else rare at your source code.
Note: This code is not mine, i got it form here at stackoverflow