Checkbox SelectedItem Text to Linq Database - c#

I built an ASP.net usercontrol and I am trying to get the text from the checkbox to pass to the database. My problem is I keep getting an error on submission with the method I use. Here is what I used:
ResidenceHallInspection rhi = new ResidenceHallInspection();
rhi.versionId = version.id;
rhi.submitDate = DateTime.Now;
rhi.CheckInOrOut = ddlCheck.SelectedItem.Text;
rhi.StudentId = txtStudentId.Text;
rhi.FirstName = txtFirstName.Text;
rhi.MiddleName = txtMiddleName.Text;
rhi.LastName = txtLastName.Text;
rhi.Walls = chbxWalls.SelectedItem.Text;
rhi.Windows = chbxWindows.SelectedItem.Text;
rhi.Blinds = chbxBlinds.SelectedItem.Text;
rhi.Couch = chbxCouch.SelectedItem.Text;
rhi.CommonRoomCouch = chbxCRCouch.SelectedItem.Text;
rhi.CommonRoomChair = chbxCRChair.SelectedItem.Text;
rhi.Doors = chbxDoors.SelectedItem.Text;
rhi.Carpet = chbxCarpet.SelectedItem.Text;
rhi.Ceiling = chbxCeiling.SelectedItem.Text;
rhi.CommonRoomCounter = chbxCRCounter.SelectedItem.Text;
rhi.Cabinet = chbxCabinet.SelectedItem.Text;
rhi.Phone = chbxPhone.SelectedItem.Text;
rhi.Bed = chbxBed.SelectedItem.Text;
rhi.Desk = chbxDesk.SelectedItem.Text;
rhi.DeskChairs = chbxDeskChair.SelectedItem.Text;
rhi.Tub = chbxTub.SelectedItem.Text;
rhi.Vanity = chbxVanity.SelectedItem.Text;
rhi.Notes = txtNotes.Text;
rhi.Building = txtResHall.Text;
rhi.ApartmentNumber = txtSuitNo.Text;
rhi.BedSpace = txtBedSpace.Text;
house.AddToResidenceHallInspections(rhi);
house.SaveChanges()

It would be good to see more information, such as the error you received, and possible the code and/or HTML for the custom user control. However, there are a couple of possibilities which seem likely. One is that your SelectedItem property may be null, which would cause an ObjectReferenceException to occur. Another is that Text itself is null, and that your database doesn't allow a null value for one or more of the fields you're assigning.
You can get a better answer than this rather vague one if you provide more information.

Related

Ramifications of using a stored procedure as a returned object as opposed to using a foreach to populate a data model?

Here are two examples of methods, the first one uses a foreach statement to populate a data model
public List<TheOrderSummary> GetTheOrderSummaryByID(int id)
{
ExoEntities = new ExoEntities();
List<TheOrderSummary> lst = new List<TheOrderSummary>();
foreach(var a in query)
{
lst.Add(new TheOrderSummary
{
OrderDetailID = a.OrderDetailID,
OrderHeaderID = a.OrderHeaderID,
ItemSeq = a.ItemSeq,
MaterialID = a.MaterialID,
Description = a.Description,
DWidth = a.DWidth,
DLength = a.DLength,
MaterialArea = a.MaterialArea.ToString(),
MaterialDetail = a.MaterialDetail,
DHeight = a.DHeight,
PurchUnitOfMeasure = a.PurchUnitOfMeasure,
SellUnitOfMeasure = a.SellUnitOfMeasure,
MaterialCategory = a.MaterialCategory,
MaterialType = a.MaterialType,
MaterialSubType = a.MaterialSubType,
ColorID = (int)a.ColorID,
Color = a.Color,
MaterialPrice = a.MaterialPrice,
MaterialCost = a.MaterialCost,
MaterialLocationID = (int)a.MaterialLocationID,
MaterialLocation = a.MaterialLocation,
LaborPrice = a.LaborPrice,
LaborCost = a.LaborCost,
VendorID = (int)a.VendorID,
VendorName = a.VendorName,
Size = a.Size,
Height = (decimal)a.Height,
Length = (decimal)a.Length,
Width = (decimal)a.Width,
PurchaseQuantity = (decimal)a.PurchaseQuantity,
SellQuantity = (decimal)a.SellQuantity,
TotalFootage = (decimal)a.TotalFootage,
GeneratedItemInd = (int)a.GeneratedItemInd,
ExtendedMaterialPrice = (decimal)a.ExtendedMaterialPrice,
ExtendedLaborCost = (decimal)a.ExtendedLaborCost,
ExtendedMaterialCost = (decimal)a.ExtendedMaterialCost
});
}
return lst;
}
and this one uses a stored procedure to return an object
public List<usp_GetTheOrderDetails_Result> GetTheOrderSummaryByID(int id)
{
ExoEntities = new ExoEntities();
var query = ExoEntities.usp_GetTheOrderDetails(id);
return query.ToList();
}
Both of these are in a DAL and the method that could call either one of these is a JSONResult, both of these can be used to populate a grid. What ramifications would using the second type be down the road as opposed to the first one? They both return the exact same thing, from the looks of it on a performance level, without doing the numbers, the second one would be faster
The pain that is introduced by returning the result directly is that you get a "hard-wired" dependency on the information contract between the consumer and the underlying data provider. If you make a change to the underlying data structure, you must update the client at the same time (which may come with various degrees of pain).
If you instead go with your first option, you encapsulate the knowledge of the underlying information structure into this layer, and may use that to map between the old and new contracts, thereby decoupling the direct dependency between the client and the data provider.
So yes, the second option might bit a tad faster (even though that really should be marginal), but the first one is likely to give you much less pain when it comes to maintaining code and deployments in the longer run.

Entity Framework C# change value in table by id

I have Estate and Contract tables. Estate table has Boolean property (Available). When clients are confirms their contract Available property in Estate table changing its value to false. Estate selects from combobox by EstateID. Problem is that I don’t know how to get access to Available property by ID selected in EstateCombobox.
contract.ContractDate = Convert.ToDateTime(ContractDateTextBox.Text);
contract.OperationType = OperationTypeComboBox.SelectedItem.ToString();
contract.Description = DescriptionTextBox.Text;
contract.EstateID = Convert.ToInt32(EstateComboBox.SelectedValue);
contract.ClientID = Convert.ToInt32(ClientComboBox.SelectedValue);
contract.EmployeeID = Convert.ToInt32(EmployeeComboBox.SelectedValue);
contract.NewOwnerID = Convert.ToInt32(NewClientOwnerComboBox.SelectedValue)
EstateComboBox.DataSource = AgencyContext.Estate.ToList();
EstateComboBox.DisplayMember = "EstateName";
EstateComboBox.ValueMember = "EstateID";
EstateComboBox.Invalidate();
I hope I understand you correctly:
int eid = Convert.ToInt32(EstateComboBox.SelectedValue.ToString());
var myEstate = AgencyContext.Estate.Single(e => e.EstateID == eid);
myEstate.Available = false; //new value
dbcontext.SaveChanges();

how to shorten this piece of C# object Oriented code?

this is my createcustomer function which returns a customer object to the caller,
getCustomerDetail returns a datatable which then populates the customer object properties with the values. Problem is whenever there's a change in the object, i have to modify this again, how do I solve this problem so that I only need to change in the Customer object and it saves my work of modifying the entire codes?
public Objects.Customer createCustomer()
{
DataTable dt = Database.Master.Customer.getCustomerDetail(objCustomer.Custcode);
objCustomer.Billaddress1 = dt.Rows[0]["Billaddress1"].ToString();
objCustomer.Billaddress2 = dt.Rows[0]["Billaddress2"].ToString();
objCustomer.Billaddress3 = dt.Rows[0]["Billaddress3"].ToString();
objCustomer.Billcontact = dt.Rows[0]["Billcontact"].ToString();
objCustomer.Billfaxno = dt.Rows[0]["Billfaxno"].ToString();
objCustomer.Billpostalcode = dt.Rows[0]["Billpostalcode"].ToString();
objCustomer.Billremarks = dt.Rows[0]["Billremarks"].ToString();
objCustomer.Billtelno = dt.Rows[0]["Billtelno"].ToString();
objCustomer.Custcode = dt.Rows[0]["Custcode"].ToString();
objCustomer.Custname = dt.Rows[0]["Custname"].ToString();
objCustomer.Doout = dt.Rows[0]["Doout"].ToString();
objCustomer.Douom = dt.Rows[0]["Douom"].ToString();
objCustomer.Inuom = dt.Rows[0]["Inuom"].ToString();
objCustomer.Location = dt.Rows[0]["Location"].ToString();
objCustomer.Outremarks1 = dt.Rows[0]["Outremarks1"].ToString();
objCustomer.Outremarks2 = dt.Rows[0]["Outremarks2"].ToString();
objCustomer.Outremarks3 = dt.Rows[0]["Outremarks3"].ToString();
objCustomer.Pacout = dt.Rows[0]["Pacout"].ToString();
objCustomer.Pacuom = dt.Rows[0]["Pacuom"].ToString();
objCustomer.Perout = dt.Rows[0]["Perout"].ToString();
objCustomer.Peruom = dt.Rows[0]["Peruom"].ToString();
objCustomer.Shipaddress1 = dt.Rows[0]["Shipaddress1"].ToString();
objCustomer.Shipaddress2 = dt.Rows[0]["Shipaddress2"].ToString();
objCustomer.Shipaddress3 = dt.Rows[0]["Shipaddress3"].ToString();
objCustomer.Shipcontact = dt.Rows[0]["Shipcontact"].ToString();
objCustomer.Shipfaxno = dt.Rows[0]["Shipfaxno"].ToString();
objCustomer.Shippostalcode = dt.Rows[0]["Shippostalcode"].ToString();
objCustomer.Shipremaks = dt.Rows[0]["Shipremaks"].ToString();
objCustomer.Shiptelno = dt.Rows[0]["BilladdresShiptelnos1"].ToString();
objCustomer.Shortname = dt.Rows[0]["Shortname"].ToString();
return objCustomer;
}
Some ideas:
Use an Object Relational Model (ORM) tool like Entity Framework or NHibernate
Use a tool like CodeSmith Generator to automatically generate this code for you
Use AutoMapper and Reflection to hydrate your object
You can use Auotamapper.
AutoMapper.Mapper.CreateMap<IDataReader, Objects.Customer>();
var results = AutoMapper.Mapper.Map<IDataReader, IList<Objects.Customer>>(dt.CreateDataReader());

Adding attributes to validator programmatically

I'm building a function to allow me to add validators into dynamically created tables. They work, in that they show up on the page and function properly. But I'm trying to add the "Display" attribute via the codebehind, and any combination of parameters fails...
RequiredFieldValidator newRQValid = new RequiredFieldValidator();
newRQValid.SetFocusOnError = true;
newRQValid.ControlToValidate = txtID;
newRQValid.Display = "dynamic"; <<---
strID = "cv" + cellID;
newRQValid.ID = strID;
newRQValid.ErrorMessage = txtErrorMessage;
newRQValid.InitialValue = initval;
tCell.Controls.Add(newRQValid);
I've tried with and without quotes, but "Dynamic" doesn't even appear in the autocomplete, so I'm assuming I'm just plain mistaken.
I have similar issues adding attributes to a compare validator as well:
CompareValidator newCMValid = new CompareValidator();
newCMValid.SetFocusOnError = true;
newCMValid.ControlToValidate = cellID;
newCMValid.ControlToCompare = "txt_clm_dob";
newCMValid.Type = ValidationDataType(DateTime); <<==
newRGValid.Display = Dynamic; <<==
strID = "cv" + cellID;
newCMValid.ID = strID;
newCMValid.ErrorMessage = txtErrorMessage;
newCMValid.Operator = LessThanEqual; <<==
tCell.Controls.Add(newCMValid);
With several attempts on each of those as well.
So what's the right syntax there, or is adding those attributes somehow not allowed here?
newRQValid.Display = ValidatorDisplay.Dynamic;
newCMValid.Type = ValidationDataType.Date;
newCMValid.Operator = ValidationCompareOperator.LessThanEqual;

How to prevent duplicate record on run time

This code cause double record...
i checked my insert code for all tables and it works fine...
and this is insert code:
StoreDO store = new StoreDO();
List<BrandDO> brandList = new BrandBL().SelectBrands();
StoreBL storeBL = new StoreBL();
store.StoreName = txtStoreName.Text;
store.StorePhone = txtStorePhone.Text;
store.StoreAddress = txtStoreAddress.Text;
store.CityID = int.Parse(ddlCity.SelectedValue);
store.CountyID = int.Parse(ddlCounty.SelectedValue);
store.IsActive = chkIsActive.Checked;
int storeID = storeBL.InsertStore(store);
ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
for (int i = 0; i < brandList.Count; i++) {
string brandName = brandList[i].BrandName.ToString() + brandList[i].BrandID.ToString();
StoreBrandBL storeBrandBL = new StoreBrandBL();
CheckBox chkBrand = (CheckBox)contentPlaceHolder.FindControl(brandName);
if (chkBrand != null) {
if (chkBrand.Checked) {
StoreBrandDO storeBrandDO = new StoreBrandDO();
storeBrandDO.StoreID = storeID;
storeBrandDO.BrandID = brandList[i].BrandID;
storeBrandDO.IsActive = true;
storeBrandBL.InsertStoreBrand(storeBrandDO);
}
}
}
Duplicating rows in your database should be avoided in the code and protected against in the database.
As hwcverwe said you can use table constraints but you should also try to set the primary key correctly for each table.
If you are using surrogate keys on all tables (such as the StoreID and BrandID I see in your code) then you will have to use unique table constraints to prevent duplicate data. Configuring your database correctly will also show up the problem areas in your code as the database will throw an exception when an insert fails.
EDIT: In response to your comment your question title is incorrect if you are asking about CheckBox controls.
Looking at the code it appears you are trying to find a checkbox control in a ContentPlaceholder but you do not show the code which creates the checkboxes.

Categories

Resources