Model doesn't accept its value - c#

This code doesn't accept the values I give with the user's department data. If i replace user.Department.ID with just a simple int variable, it works fine. This is also the problem with user.Department.Code and user.Department.Title. I don't know what's the problem. Is it in my models?
This is the code. The system queries for the user data. I believe that the query is fine. I'm using a connection string with MS Access btw.
try
{
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
UserModel user = new UserModel();
if (!reader.IsDBNull(0))
{
user.Id = reader.GetInt32(0);
}
if (!reader.IsDBNull(1))
{
user.Department.Id = reader.GetInt32(1);
}
if (!reader.IsDBNull(2))
{
user.Department.Code = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
user.Department.Title = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
user.FamilyName = reader.GetString(4);
}
if (!reader.IsDBNull(5))
{
user.GivenName = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
user.MiddleName = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
user.NameSuffix = reader.GetString(7);
}
if (!reader.IsDBNull(8))
{
user.Type = reader.GetString(8);
}
CurrentUser = user;
CanLogin = true;
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception Error");
}
Here is my Usermodel...
class UserModel
{
public int Id { get; set; }
public DepartmentModel Department { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string NameSuffix { get; set; }
public string Type { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName(bool isFamilyNameFirst)
{
StringBuilder fullname = new StringBuilder();
if(isFamilyNameFirst)
{
fullname.Append(FamilyName).Append(", ").Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(NameSuffix);
}
else
{
fullname.Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(FamilyName).Append(" ").Append(NameSuffix);
}
return fullname.ToString();
}
}
And my Department Model..
class DepartmentModel
{
public int Id { get; set; }
public InstitutionModel Institution { get; set; }
public string Code { get; set; }
public string Title { get; set; }
}

The Department property never initialize any where, you an do it in user constructor:
class UserModel
{
public UserModel()
{
this.Department = new DepartmentModel();
}
public int Id { get; set; }
public DepartmentModel Department { get; set; }
public string FamilyName { get; set; }
public string GivenName { get; set; }
public string MiddleName { get; set; }
public string NameSuffix { get; set; }
public string Type { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FullName(bool isFamilyNameFirst)
{
StringBuilder fullname = new StringBuilder();
if(isFamilyNameFirst)
{
fullname.Append(FamilyName).Append(", ").Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(NameSuffix);
}
else
{
fullname.Append(GivenName).Append(" ").Append(MiddleName).Append(" ").Append(FamilyName).Append(" ").Append(NameSuffix);
}
return fullname.ToString();
}
}
Or
UserModel user = new UserModel() {Department = new DepartmentModel()};

Related

using jsonData as a key value to send mixed data in asp: Does not update the database with the values

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.

Using Dapper in method context to return multiple lists

I have a vendor class like this:
public class Vendor: DataAccess
{
//properties
public int VEND_ID;
public string VEND_NAME { get; set; }
public string VEND_ADDRESS { get; set; }
public string VEND_PHONE { get; set; }
public string VEND_WEBSITE { get; set; }
public string NOTES { get; set; }
public static string ErrorMessage { get; set; }
//Constructors
public Vendor(string name,string address,string phone,string website,string notes)
{
VEND_NAME = name;
VEND_ADDRESS = address;
VEND_PHONE = phone;
VEND_WEBSITE = website;
NOTES = notes;
}
public Vendor(string name)
{
VEND_NAME = name;
}
public Vendor() { }
)
I have an Orders Class like this:
public class Order: DataAccess
{
//properties
public int ORDER_ID { get; set; }
public Vendor VENDOR_ID { get; set; }
public string ENTRY_DATE { get; set; }
public string ORDER_NO { get; set; }
public string TOTAL_COST { get; set; }
public string STATUS { get; set; }
public string NOTES { get; set; }
public string ATTACH_ID { get; set; }
public static string ErrorMessage { get; set; }
//constructors
//public Order(string )
}
My Data Access Class has the following method:
public Tuple<List<Vendor>, List<Order>> GetVendorByName(string name)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("TESTDB")))
{
using (var multi = connection.QueryMultiple("dbo.GetVendor_ByName", new { VEND_NAME = name }))
{
List<Vendor> vd=new List<Vendor>();
vd.Add(multi.Read<Vendor>().First());
List<Order> od = new List<Order>();
od.Add(multi.Read<Order>().Single());
var output = Tuple.Create(vd, od);
return output;
}
//var output = connection.QueryMultiple<Vendor>("dbo.GetVendor_ByName", new { VEND_NAME = name }).ToList();
}
}
The main class uses it like this:
List<Vendor> vendor = new List<Vendor>();
private void _search_Click(object sender, EventArgs e)
{
Vendor db = new Vendor(cb_vendor.Text);
vendor=db.GetVendorByName(cb_vendor.Text);//This is where the error is pointed at
//dgv_data.Refresh();
dgv_data.DataSource = vendor;
}
I am trying to get the data from the SQL procedure to show in the DataGridView (dgv_data). There is a one to many relation between Vendor and Order. I want to get all the Orders for whatever Vendor Name is selected
I know the issue is that I am returning List. I tried using Tuples but no joy, it gives me an error about implicit conversions. Any idea how to do what I am trying to accomplish?
Error CS0029 Cannot implicitly convert type
'System.Tuple,
System.Collections.Generic.List>' to
'System.Collections.Generic.List' PurchApp
Update1:
The stored procedure is like this:
ALTER proc [dbo].[GetVendor_ByName]
(
#VEND_NAME varchar(100)
)
as
Select Distinct a.VEND_NAME,b.* from dbo.Purch_Vendor a left join purch_order b on a.vendor_id=b.vendor_id where a.Vend_Name=#VEND_NAME
Try this. It maps orders to the vendor on name. I have added a property for List of Orders to the Vendor
public class Vendor : DataAccess
{
//properties
public int VEND_ID;
public string VEND_NAME { get; set; }
public string VEND_ADDRESS { get; set; }
public string VEND_PHONE { get; set; }
public string VEND_WEBSITE { get; set; }
public string NOTES { get; set; }
public List<Order> ORDERS { get; set; }
public static string ErrorMessage { get; set; }
//Constructors
public Vendor(string name, string address, string phone, string website, string
notes)
{
VEND_NAME = name;
VEND_ADDRESS = address;
VEND_PHONE = phone;
VEND_WEBSITE = website;
NOTES = notes;
}
public Vendor(string name)
{
VEND_NAME = name;
}
public Vendor() { }
}
public class Order : DataAccess
{
//properties
public int ORDER_ID { get; set; }
public Vendor VENDOR_ID { get; set; }
public string ENTRY_DATE { get; set; }
public string ORDER_NO { get; set; }
public string TOTAL_COST { get; set; }
public string STATUS { get; set; }
public string NOTES { get; set; }
public string ATTACH_ID { get; set; }
public static string ErrorMessage { get; set; }
//constructors
//public Order(string )
}
public Vendor GetVendorByName(string name)
{
using (IDbConnection connection = new
SqlConnection(Helper.CnnVal("TESTDB")))
{
var dict = new Dictionary<string, Vendor>();
var vendors = connection.Query<Vendor, Order, Vendor>
("dbo.GetVendor_ByName", (a, b) => Mapper(a, b, dict), new {
VEND_NAME = name }, splitOn: "ORDER_ID");
return dict.Values.FirstOrDefault()
}
}
public Vendor Mapper(Vendor vendor, Order order, Dictionary<string, Vendor> dict)
{
if (!dict.ContainsKey(vendor.VEND_NAME))
{
vendor.ORDERS = new List<Order>();
dict.Add(vendor.VEND_NAME, vendor);
}
var currentVendor = dict[vendor.VEND_NAME];
currentVendor.ORDERS.Add(order);
return currentVendor;
}

Most efficient way to compare an Entity Model to a DTO Model in C#/LINQ

I am passing back a DTO object with a more than a dozen properties that I want to update in the database only if one or more of the properties differ with the current EF object. What is the most programmatically simple way to accomplish this using C# and Lambda-syntax LINQ?
Try this example.
[HttpPost]
[Route("Client/UpdateClient")]
[Authorize]
public ActionResult UpdateClient(ClientDTO client)
{
var user = GetLoggerUser(BOAccount);
client.LastModifiedBy = user.EmailAddress;
client.LastModifiiedOn = DateTime.UtcNow;
var resultclient = BOClient.UpdateClient(client, user);
return Json(resultclient);
}
// BOClient.UpdateClient
public ClientDTO UpdateClient(ClientDTO client, UserDTO user)
{
var _clientRepo = ((UnitOfWork)_unitOfWork).ClientRepository;
var _client = _clientRepo.Get(filter: u => u.Id == client.Id).Single();
_client.Id = client.Id;
_client.Phone = client.Phone;
_client.Address = client.Address;
_client.Email = client.Email;
_client.Type = client.Type;
_client.Name = client.Name;
object _transaction = _unitOfWork.BeginTransaction();
try
{
_clientRepo.Update(_client);
_unitOfWork.CommitTransaction(_transaction);
}
catch (Exception)
{
_unitOfWork.RollbackTransaction(_transaction);
return client;
}
finally
{
_unitOfWork.DestroyTransaction(_transaction);
}
return client;
}
And Created model is
namespace OptiLeadInfrastructure.Models
{
public class ClientDTO
{
public long Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public Nullable<short> Type { get; set; }
public string logo { get; set; }
public Nullable<DateTime> CreatedOn { get; set; }
public string CreatedBy { get; set; }
public Nullable<DateTime> LastModifiiedOn { get; set; }
public virtual ICollection<ClientDetailDTO> ClientDetails { get; set; }
} public string LastModifiedBy { get; set; }
}

C# sort datagridview on column header click

:)
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

Runtime error when data is passed from View to Action method

I am getting a runtime error in a browser when tried to pass data from view to post Action method.
Error:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
This is my Action Method:
MyContext db = new MyContext();
public ActionResult SaveGen(Enroll_Gen Enrollment,HttpPostedFileBase file)
{
int i = UploadDataInDataBase(file,Enrollment);
if (i == 1)
{
return RedirectToAction("Index");
}
return RedirectToAction("Guardian");
}
public int UploadDataInDataBase(HttpPostedFileBase file, Enroll_Gen EnrollGEn)
{
EnrollGEn.Photo = ConvertToBytes(file);
var Enroll_Gen = new Enroll_Gen
{
AdmnNum = EnrollGEn.AdmnNum,
Class = EnrollGEn.Class,
Section = EnrollGEn.Section,
AcademicYear_Batch = EnrollGEn.AcademicYear_Batch,
DateOfAdmission=EnrollGEn.DateOfAdmission,
RollNum =EnrollGEn.RollNum,
Regt_Numb = EnrollGEn.Regt_Numb,
Photo = EnrollGEn.Photo,
FirstName=EnrollGEn.FirstName,
MiddleName=EnrollGEn.MiddleName,
LastName=EnrollGEn.LastName,
DOB=EnrollGEn.DOB,
Mobile=EnrollGEn.Mobile,
Gender=EnrollGEn.Gender,
Nationality=EnrollGEn.Nationality,
Language=EnrollGEn.Language,
Religion=EnrollGEn.Religion,
BloodGroup=EnrollGEn.BloodGroup,
Address=EnrollGEn.Address,
Country=EnrollGEn.Country,
State=EnrollGEn.State,
City=EnrollGEn.City,
PinCode=EnrollGEn.PinCode,
WebUrl=EnrollGEn.WebUrl
};
db.Enroll_Gens.Add(Enroll_Gen);
int i = db.SaveChanges();
if (i == 1)
{
return 1;
}
else
{
return 0;
}
}
public byte[] ConvertToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}
this is Model class:
public partial class Enroll_Gen
{
public Enroll_Gen()
{
this.Entrance = new HashSet<Entrance>();
this.QualNAchi = new HashSet<QualNAchi>();
this.Scholarship = new HashSet<Scholarship>();
}
[Key]
public string AdmnNum { get; set; }
public string Class { get; set; }
public string Section { get; set; }
public int AcademicYear_Batch { get; set; }
public string DateOfAdmission { get; set; }
public int RollNum { get; set; }
public string Regt_Numb { get; set; }
public byte[] Photo { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string DOB { get; set; }
public string Mobile { get; set; }
public string Gender { get; set; }
public string Nationality { get; set; }
public string Language { get; set; }
public string Religion { get; set; }
public string BloodGroup { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public string State { get; set; }
public string City { get; set; }
public string PinCode { get; set; }
public string WebUrl { get; set; }
public virtual ICollection<Entrance> Entrance { get; set; }
public virtual ICollection<QualNAchi> QualNAchi { get; set; }
public virtual ICollection<Scholarship> Scholarship { get; set; }
}

Categories