Get ID value from combo box with entity framework - c#

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;
}

Related

how to get all the items of list c#

In a list i have 4 rows and I am try to get all the rows of the list but it is giving only one row, how to get all the rows of the list.
I have tried below code
public async Task<ResponseUserModel> get()
{
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
using (nae2sasqld0003Entities context = new nae2sasqld0003Entities())
{
var listt = context.Producers.Select(all => all).ToList();
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
}
}
please let me know where i to fix the issue
Use list to return all:
List<ResponseUserModel> responseUsers = new List<ResponseUserModel>();
then
foreach (var item in listt)
{
responseUsers.Add(new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
});
}
return responseUsers;
Note: change return type of the method to IList<ResponseUserModel>
or in this way
using (var context = new nae2sasqld0003Entities())
{
return context.Producers.Select(item =>
new ResponseUserModel
{
ProducerName = item.ProducerName,
ResidentState = item.ResidentState,
ResidentCity = item.ResidentCity,
ProducerStatus = item.ProducerStatus,
ProducerCode = item.ProducerCode,
MasterCode = item.MasterCode,
NationalCode = item.NationalCode,
LegacyChubbCodes = item.LegacyChubbCodes,
LegacyPMSCode = item.LegacyPMSCode,
ProducingBranchCode = item.ProducingBranchCode,
CategoryCode = item.CategoryCode
}).ToList();
}

Load Windows form after complete combobox data load in c#

I have a form for employees called frmEmployees where I need to load couple of combo box with data like country, category, nationality, such others.
Now when user click on to open frmEmployees, window is stuck for bit and then open. I assume that this is because of data loading and initializing the combo box.
Now! what I want is, just after click on button to open frmEmployees run a progress bar till data loading complete and then open form.
public frmEmployee()
{
InitializeComponent();
con = new Connection();
LoadComboboxDS();
}
I have tried also
private void FrmEmployee_Load(object sender, EventArgs e)
{
LoadComboboxDS();
}
private void LoadComboboxDS()
{
//company
var _companies = con.Companies.Where(x => x.IsDeleted == false).ToList();
_companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = _companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
//gender
cbGender.DataSource = Enum.GetValues(typeof(Gender));
//merital status
cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));
//citizenship
var _citizenships = con.Countries.Select(x => x.Citizenship).Distinct().ToList();
_citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
//nationality
var _nations = con.Countries.Select(x => x.Name).Distinct().ToList();
_nations.Insert(0, "--Select--");
cbNationality.DataSource = _nations;
cbNationality.DisplayMember = "Name";
//domicile
var _domiciles = con.Countries.Select(x => x.Name).Distinct().ToList();
_domiciles.Insert(0, "--Select--");
cbDomicile.DataSource = _domiciles;
cbDomicile.DisplayMember = "Name";
//cast category
var _casts = con.CastCategories.Select(x => new {x.ShortText, x.Description}).Distinct().ToList();
_casts.Insert(0, new { ShortText = "", Description = "--Select--" });
cbCategory.DataSource = _casts;
cbCategory.DisplayMember = "Description";
cbCategory.ValueMember = "ShortText";
//religion
cbReligion.DataSource = Enum.GetValues(typeof(Religion));
}
You can use Async extension methods of Entity Framework 6 to make your code asynchronous.
Separate your data access and presentation layer, at first:
public static class MyRepository // consider not static, just an example
{
public static async Task<List<Company>> GetCompanies()
{
using (var connection = new Connection()) // consider factory
{
return await con.Companies.Where(x => x.IsDeleted == false).ToListAsync();
}
}
public async Task<List<Citizenship>> GetCitizenships()
{
using (var connection = new Connection()) // factory?
{
return await con.Countries.Select(x => x.Citizenship).Distinct().ToList();
}
}
}
Then, you can run all these tasks at once and wait for them to complete:
// Wherever you are going to open frmEmployee
public async Task openFrmEmployee_OnClick(object sender, EventArgs e)
{
var getCompaniesTask = MyRepository.GetCompanies();
var getCitizenshipsTask = MyRepository.GetCitizenships();
await Task.WhenAll(getCompaniesTask, getCitizenshipsTask); // UI thread is not blocked
var form = new FrmEmployee(getCompaniesTask.Result, getCitizenshipsTask.Result); // form is created with data
}
Now, you only need to make your form accept complete data in constructor instead of making your form load this data which breaks abstraction:
public class FrmEmployees
{
public FrmEmployees(List<Company> companies, List<Citizenship> citizenships)
{
companies.Insert(0,new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
// etc.
}
}
One important thing: you can get many tasks and many data passed to a form constructor. If all this data is going to be used often togetther, then you would probably want to encapsulate this "get all these things" logic into a single place to remove possible code duplication.
See what I have done... if anyone can review my code it would be appreciable.
public class EmployeeFormDataRepesenter
{
public List<Company> Companies { get; set; }
public List<Country> Countries { get; set; }
public List<CastCategory> CastCategories { get; set; }
}
public void LoadData(EmployeeFormDataRepesenter representer)
{
//gender
cbGender.DataSource = Enum.GetValues(typeof(Gender));
//merital status
cbMeritalStatus.DataSource = Enum.GetValues(typeof(MaritalStatus));
//religion
cbReligion.DataSource = Enum.GetValues(typeof(Religion));
//company
var _companies = representer.Companies;
_companies.Insert(0, new data.Models.CompanyModels.Company { Address = new data.Models.Address(), Code = null, Name = "--Select--", BaseCurrency = new data.Models.Currency() });
cbCompany.DataSource = _companies;
cbCompany.DisplayMember = "Name";
cbCompany.ValueMember = "ID";
//citizenship
var _citizenships = representer.Countries.Select(x => x.Citizenship).ToList();
_citizenships.Insert(0, "--Select--");
cbCitizenship.DataSource = _citizenships;
cbCitizenship.DisplayMember = "Citizenship";
//nationality
var _nations = representer.Countries.Select(x => x.Name).ToList();
_nations.Insert(0, "--Select--");
cbNationality.DataSource = _nations;
cbNationality.DisplayMember = "Name";
//domicile
var _domiciles = representer.Countries.Select(x => x.Name).ToList();
_domiciles.Insert(0, "--Select--");
cbDomicile.DataSource = _domiciles;
cbDomicile.DisplayMember = "Name";
//cast category
var _casts = representer.CastCategories.Select(x => new { x.ShortText, x.Description }).Distinct().ToList();
_casts.Insert(0, new { ShortText = "", Description = "--Select--" });
cbCategory.DataSource = _casts;
cbCategory.DisplayMember = "Description";
cbCategory.ValueMember = "ShortText";
}
private async void btnEmplyee_Click(object sender, EventArgs e)
{
con = new Connection();
Action showProgress = () => frmStatrup._progressBar.Visible = true;
Action hideProgress = () => frmStatrup._progressBar.Visible = false;
EmployeeFormDataRepesenter representer;
Task<List<Company>> _taskCompany = new Task<List<Company>>(() =>
{
BeginInvoke(showProgress);
var list = con.Companies.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
Task<List<Country>> _taskCountry = new Task<List<Country>>(() =>
{
BeginInvoke(showProgress);
var list = con.Countries.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
Task<List<CastCategory>> _taskCasts = new Task<List<CastCategory>>(() =>
{
BeginInvoke(showProgress);
var list = con.CastCategories.ToListAsync();
BeginInvoke(hideProgress);
if (list != null)
return list.Result;
return null;
});
_taskCompany.Start();
var _companies = await _taskCompany;
_taskCountry.Start();
var _countries = await _taskCountry;
_taskCasts.Start();
var _casts = await _taskCasts;
if (_companies.Count != 0)
{
representer = new EmployeeFormDataRepesenter();
representer.Companies = _companies;
representer.Countries = _countries;
representer.CastCategories = _casts;
}
else
{
representer = null;
}
if (representer != null)
{
frmEmployee _emp = new frmEmployee();
_emp.LoadData(representer);
Functions.OpenForm(_emp, this.ParentForm);
}
}

Listing in WCF Entity

I have a problem with LINQ query (see comment) there is a First method and it only shows me the first element.
When I write in the console "Sales Representative" it shows me only the first element of it as in
I would like to get all of data about Sales Representative. How can I do it?
public PracownikDane GetPracownik(string imie)
{
PracownikDane pracownikDane = null;
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
//Employee matchingProduct = database.Employees.First(p => p.Title == imie);
var query = from pros in database.Employees
where pros.Title == imie
select pros;
// Here
Employee pp = query.First();
pracownikDane = new PracownikDane();
pracownikDane.Tytul = pp.Title;
pracownikDane.Imie = pp.FirstName;
pracownikDane.Nazwisko = pp.LastName;
pracownikDane.Kraj = pp.Country;
pracownikDane.Miasto = pp.City;
pracownikDane.Adres = pp.Address;
pracownikDane.Telefon = pp.HomePhone;
pracownikDane.WWW = pp.PhotoPath;
}
return pracownikDane;
}
Right now you are just getting the .First() result from the Query collection:
Employee pp = query.First();
If you want to list all employees you need to iterate through the entire collection.
Now, if you want to return all the employee's you should then store each new "pracownikDane" you create in some sort of IEnumerable
public IEnumerable<PracownikDane> GetPracownik(string imie) {
using (NORTHWNDEntities database = new NORTHWNDEntities())
{
var query = from pros in database.Employees
where pros.Title == imie
select pros;
var EmployeeList = new IEnumerable<PracownikDane>();
foreach(var pp in query)
{
EmployeeList.Add(new PracownikDane()
{
Tytul = pp.Title,
Imie = pp.FirstName,
Nazwisko = pp.LastName,
Kraj = pp.Country,
Miasto = pp.City,
Adres = pp.Address,
Telefon = pp.HomePhone,
WWW = pp.PhotoPath
});
}
return EmployeeList;
}
Then, with this returned List you can then do what ever you wanted with them.

Entity Framework 5 will not allow .SaveChanges

I've upgraded to Entity Framework 5 and the .SaveChanges is no longer available.
How do we save our changes?
When ever I do a db.SaveChanges(); it errors because .SaveChanges is not there.
static bool Insert(Elevation elevation, out Elevation elevationOUT)
{
using (var db = new StorefrontSystemEntities())
{
//erik#afbs.net : DA91DC34-FA29-4ABD-BCC0-D04408310E3E
//projectID = 12
elevationOUT = null;
var projs = from p in db.Projects
where p.ID == elevation.ProjectID
select p;
//
var proj = projs.SingleOrDefault();
if (proj == null) { return false; }
//Elevation
var elev = new Elevation
{
ID = proj.ID,
Name = elevation.Name,
Note = elevation.Note,
ComponentID = elevation.CompID,
VerCutHD = elevation.VerCutHD,
VerCutSill = elevation.VerCutSill,
Created = DateTime.Now
};
proj.Elevations.Add(elev);
//Bays
foreach (var bay in elevation.Bays)
{
var b = new Bay
{
Position = bay.Position,
IsBulkhead = bay.IsBulkhead,
Note = bay.Note,
Size = GetClientSize(bay.Size),
IsFixed = bay.IsFixed,
Finish = GetClientFinish(bay.Finish),
Siteline = GetClientSiteline(bay.Siteline, elev.ComponentID),
VerCutHD = elevation.VerCutHD,
VerCutSill = elevation.VerCutSill
//
};
elev.Bays.Add(b);
};
db.SaveChanges();
elevationOUT = elev;
elevationOUT.IsGeneric = proj.GenericCatalogID > 0;
}
return true;
}

Error when returning value in C# 2.0

I downloaded an example application for using some web services with an online system.
I am not sure if all code below is needed but it is what I got and what I am trying to do is to use the search function.
I start by calling searchCustomer with an ID I have:
partnerRef.internalId = searchCustomer(customerID);
And the code for searchCustomer:
private string searchCustomer(string CustomerID)
{
string InternalID = "";
CustomerSearch custSearch = new CustomerSearch();
CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();
String nameValue = CustomerID;
SearchStringField entityId = null;
entityId = new SearchStringField();
entityId.#operator = SearchStringFieldOperator.contains;
entityId.operatorSpecified = true;
entityId.searchValue = nameValue;
custSearchBasic.entityId = entityId;
String statusKeysValue = "";
SearchMultiSelectField status = null;
if (statusKeysValue != null && !statusKeysValue.Trim().Equals(""))
{
status = new SearchMultiSelectField();
status.#operator = SearchMultiSelectFieldOperator.anyOf;
status.operatorSpecified = true;
string[] nskeys = statusKeysValue.Split(new Char[] { ',' });
RecordRef[] recordRefs = new RecordRef[statusKeysValue.Length];
for (int i = 0; i < nskeys.Length; i++)
{
RecordRef recordRef = new RecordRef();
recordRef.internalId = nskeys[i];
recordRefs[i] = recordRef;
}
status.searchValue = recordRefs;
custSearchBasic.entityStatus = status;
}
custSearch.basic = custSearchBasic;
SearchResult response = _service.search(custSearch);
if (response.status.isSuccess)
{
processCustomerSearchResponse(response);
if (seachMoreResult.status.isSuccess)
{
processCustomerSearchResponse(seachMoreResult);
return InternalID;
}
else
{
_out.error(getStatusDetails(seachMoreResult.status));
}
}
else
{
_out.error(getStatusDetails(response.status));
}
return InternalID;
}
In the code above processCustomerSearchResponse gets called
processCustomerSearchResponse(response);
The code for this function is:
public string processCustomerSearchResponse(SearchResult response)
{
string InternalID = "";
Customer customer;
customer = (Customer)records[0];
InternalID = customer.internalId;
return InternalID;
}
What the original code did was to write some output in the console but I want to return the InternalID instead. When I debug the application InternalID in processCustomerSearchResponse contains the ID I want but I don't know how to pass it to searchCustomer so that function also returns the ID. When I debug searchCustomer InternalID is always null. I am not sure on how to edit the code under response.status.isSuccess
to return the InternalID, any ideas?
Thanks in advance.
When you call processCustomerSearchResponse(response);, you need to store the return value in memory.
Try modifying your code like this:
InternalID = processCustomerSearchResponse(response);

Categories