Invalid operation exception was unhandled - c#

I am trying to delete the record from an entity
got an error: Invalid operation exception
The object cannot be deleted because it was not found in the ObjectStateManager.
and the code is like this...
private void btnProdDelete_Click(object sender, EventArgs e){
Image image = pictureBox1.Image;
byte[] bit = null;
bit = imageToByteArray(image);
//var c = new category {
// category_Name = tbCategoryName.Text,
// category_Description = tbCategoryDescription.Text
//};
product pd = new product();
pd.product_Id = productid;
pd.product_Name = tbProductName.Text;
decimal price = Convert.ToDecimal(tbProductPrice.Text);
pd.product_Price = price;
pd.product_Description = tbProductdescription.Text;
pd.product_Image = bit;
tsgentity.DeleteObject(pd);
this.Close();
}
would any one pls help on this...
Modified code :
public partial class ProductDescriptionForm : Form {
public TsgEntities tsgentity;
public ProductDescriptionForm() {
InitializeComponent();
tsgentity = new TSGEntities();
}

The problem is that you are trying to delete an object that is not tracked by the context.
The proper way to delete without fetching is to create an instance (only the id is actually needed), attach it to the context and then delete it :
var pd =
new product()
{
product_Id = productid,
EntityKey = new EntityKey("product.id", "id", productid)
};
tsgentity.Attach(pd);
tsgentity.DeleteObject(pd);

Related

Xamarin forms stacklayout returning null

I tried to get the item on stacklayout into an SQLite Database, but it just won't carry any data with.
private void MainCategory_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var carier = e.SelectedItem as Item;
var cart_Itemsx = new List<cart_Items>();
cart_Itemsx.Add(new Models.cart_Items { cartid = 1, Id = carier.itid, image = carier.image, name = carier.title, price = carier.price1, quantity = "1", type = "Wash and Iron" });
cart_Itemsx.Add(new Models.cart_Items { cartid = 2, Id = carier.itid, image = carier.image, name = carier.title, price = carier.price2, quantity = "1", type = "Iron Only" });
SubCategory.ItemsSource = cart_Itemsx.ToList();
}
private void SubCategory_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var dbcontet = e.SelectedItem as cart_Items;
_dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "WashPro.db3");
var db = new SQLiteConnection(_dbPath);
db.CreateTable<cart_Items>();
var MaximumPrimaryKey = db.Table<cart_Items>().OrderByDescending(zt => zt.cartid).FirstOrDefault();
var waltani = new cart_Items()
{
cartid = (MaximumPrimaryKey == null ? 1 : MaximumPrimaryKey.cartid + 1),
Id = dbcontet.Id,
image = dbcontet.image,
name = dbcontet.name,
price = dbcontet.price,
quantity = dbcontet.quantity,
type = dbcontet.quantity
};
if (MaximumPrimaryKey == null)
{
db.Insert(waltani);
}
else if (MaximumPrimaryKey != null)
{
var MaximumQuantityKey = db.Table<cart_Items>().Where(m => m.cartid.Equals(dbcontet.cartid) && m.type.Equals(dbcontet.type)).FirstOrDefault();
if (MaximumQuantityKey != null)
{
waltani.price = dbcontet.price = 1;
db.Update(waltani);
}
}
SubCategory.SelectedItem = null;
}
image of the null error I got
I cannot even begin to understand the problem. The way I found around the problem will make my already dirty code way dirtier.
I have the damaging method I tried was using the selected context of the main stack panel to influence the second stack pannel.
I have even made the primary key of the cart_item model null.
Your selected element is null or database table does not contain any elements you are looking for in query, which is more likely because you are trying to initialize your database on SubCategory_ItemSelected. This is wrong approach.
Try to check if database item exist first.
var exist = db.Table<cart_Items>().OrderByDescending(zt => zt.cartid).Any();
if (exist)
{
var MaximumPrimaryKey = db.Table<cart_Items>().OrderByDescending(zt => zt.cartid).FirstOrDefault();
var waltani = new cart_Items()
{
cartid = (MaximumPrimaryKey == null ? 1 : MaximumPrimaryKey.cartid + 1),
Id = dbcontet.Id,
image = dbcontet.image,
name = dbcontet.name,
price = dbcontet.price,
quantity = dbcontet.quantity,
type = dbcontet.quantity
};
}
The problem lies at the last line of code.
SubListview.SelectedItem = null;
This somehow makes the casting not see the e.selected items.

DataBind into DB from Class in asp.net

I'm filling up a database from an aspx web application.
Everything works fine, except for the fact that I use multiple pages for users to fill in their data into DB.
So, i got this method in one class.cs file:
public class Botones
{
public void SaveCVInfo2(string varOne,string varTwo, string varThree)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
This is just a part of the file, it has more columns, but it doesn't change the example.
However, I added another class.cs file in order to reference it's method from a button in the second page. Just like the one I posted before in this post:
public class Botones2
{
public void SaveCVInfo3(string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
}
AS you can see there are more columns I'm filling into the db, in the same table, problem is, when i submit data to the sql server, from second page, it just creates a new Usuario_web without the columns i referenced in first class.
What i need is to bind somehow the data already sent from first page. So first class is associated with all other classes, and columns are filled in the same row.
If anybody knows how to handle this situation, please let me know.
EDIT
This is how i call methods from asp buttons:
protected void Button1_Click(object sender, EventArgs e)
{
Botones botones = new Botones();
botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
}
And SaveCVInfo3:
protected void Button1_Click(object sender, EventArgs e)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
CAUTION: Untested code below.
I would return the columna.ID from SaveCVInfo2:
public int SaveCVInfo2(string varOne,string varTwo, string varThree)
{
int columnaId = 0;
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
Usuario_Web columna = new Usuario_Web();
//Add new values to each fields
columna.Nombre = varOne;
columna.Apellido = varTwo;
columna.Em_solicitado = varThree;
//and the rest where the textboxes would have been
//Insert the new Customer object
db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
columnaId = columna.ID;
}
return columnaId;
}
And call the method, get the ID and save in the Session like this:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
Botones botones = new Botones();
columnaId = botones.SaveCVInfo2(nombre.Text, Apellidos.Text, EmpleoS.Text);
Session["columnaId"] = columnaId.ToString();
}
Now when calling the SaveCVInfo3 method, I can pass the columnaId:
protected void Button1_Click(object sender, EventArgs e)
{
int columnaId = 0;
if(Session["columnaId"] != null && int.TryParse(Session["columnaId"].ToString(), out columnaId)
{
Botones2 botones2 = new Botones2();
botones2.SaveCVInfo3(columnaId, nombre_compa.Text, Profesion_compa.Text, Emp_trabaja.Text, Cargo_compa.Text, RadioButtonList8.SelectedItem.Text, edades_sons.Text, num_depende.Text, Afinidad.Text, Edad_compa.Text, nom_padre.Text, profesion_compa_padre.Text, Tel_compa.Text, nom_madre.Text, profesion_compa_madre.Text, Tel_compa_madre.Text);
Response.Redirect("Envia3.aspx");
}
}
And in SaveCVInfo3 method I would get the object by Id, which is already saved in previous page and edit it, save it:
public void SaveCVInfo3(int columnaId, string varOne, string varTwo, string varThree, string varFour, string varFive, string varSix, string varSeven,
string varEight, string varNine, string varTen, string varEleven, string varTwelve, string varThirteen, string varFourteen, string varFifteen)
{
using (ConexionGeneralDataContext db = new ConexionGeneralDataContext())
{
//You will need to add reference to Linq if not added already
//Usuario_Web columna = new Usuario_Web();
//Insert the new Customer object
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
columna.Estatus = 1;
columna.nombre_esposo = varOne;
columna.profe_compa = varTwo;
columna.emp_compa = varThree;
columna.cargo_actual_compa = varFour;
columna.Hijos = varFive;
columna.Edades_hijos = varSix;
columna.persona_depende_compa = varSeven;
columna.afinidades = varEight;
columna.Edades_depende = varNine;
columna.nom_padre = varTen;
columna.profesion_padre = varEleven;
columna.tel_padre = varTwelve;
columna.nom_madre = varThirteen;
columna.profesion_madre = varFourteen;
columna.tel_madre = varFifteen;
//db.Usuario_Web.InsertOnSubmit(columna);
//Sumbit changes to the database
db.SubmitChanges();
}
}
EDIT If Id is not a primary key, you can change this part-
Usuario_Web columna = (Usuario_Web)db.Usuario_Webs.Find(columnaId);
to :
Usuario_Web columna =(Usuario_Web)db.Usuario_Web.Where(x=>x.ID == columnaId).FirstOrDefault()

null Amount value salesorderdetail on crm 2011-Silverlight

I'm trying to insert data on SalesOrderDetail entity, everything works fine, except for the Amount field which remains null. I don't get any error message.
Here is an example of my code :
private void beginCreateSalesOrderDetail()
{
SalesOrderDetail orderDetail = new SalesOrderDetail();
orderDetail.SalesOrderId = new EntityReference()
{
Id = id,
LogicalName = "salesorder"
};
orderDetail.Quantity = element.QuantityOnHand;
orderDetail.ProductId = new EntityReference()
{
Id = element.ProductId,
LogicalName = "product"
};
orderDetail.UoMId = new EntityReference()
{
Id = new Guid("8DDD2AFB-73CF-E111-8140-00155D55B216"),
LogicalName = "uom"
};
orderDetail.TransactionCurrencyId = new EntityReference()
{
Id = new Guid("77D695B5-ACB4-E111-97BC-00155D55B216"),
LogicalName = "transactioncurrency"
};
Money Taxe = new Money();
Money Amount = new Money();
Taxe.Value = Convert.ToDecimal(element.totalCharges);
Amount.Value = Convert.ToDecimal(InvoiceTotal);
orderDetail.Tax = Taxe;
orderDetail.BaseAmount = Amount;
orderDetail.PricePerUnit = element.Price;
orderDetail.Description = element.PDesc;
_context.AddToSalesOrderDetailSet(orderDetail);
_context.BeginSaveChanges(EndCreateSalesOrderDetail, orderDetail);
}
private void EndCreateSalesOrderDetail(IAsyncResult result)
{
try
{
_context.EndSaveChanges(result);
}
catch (Exception ex)
{
}
}
Please note that only the amount which remains null
I get the solution.
Actually, there is a restrictions in crm 2011 to calcul the amounts of products,
We have to create a Price List, and associate each product in the list.
Thank you.

Comparing Arrays and Create data into database

I'm now stuck regarding array comparison and creating it. I have 2 tables, station and location. The columns inside station is the id and the station name. there goes the same to the location table only different is the name. I put the id into a array and the name to the array. I wanted to compare the name and the id so that when user select the name, the program knows which id belongs to the selected name and save it into the other table using their primary keys. Here were the codes that I created from now but I don't know how to solve it. Hope I could get some help here. Thanks!
private void btnCreate_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
string[] stations = StationNameList();
int[] stationsID = StationIDList();
string[] locations = LocationNameList();
int[] locationsID = LocationIDList();
int Stationindex = cbStation.SelectedIndex;
int Locationindex = cbLocation.SelectedIndex;
trolleyservice TS = new trolleyservice();
TS.stationID = cbStation.SelectedIndex;
TS.locationID = cbLocation.SelectedIndex;
TS.tServiceTiming = txtTime.Text;
TS.tServiceType = txtType.Text;
Setupctx.trolleyservices.AddObject(TS);
txtTime.Text = "";
txtType.Text = "";
MessageBox.Show("New Trolley Service Has Been Created.");
}
}
Here were all the arrays that I created for each tables.
private string[] StationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.Select(s => s.Station1).OrderBy(s => s).ToArray();
}
}
private int[] StationIDList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.Select(sid => sid.idstations).OrderBy(sid => sid).ToArray();
}
}
private string[] LocationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.locations.Select(l => l.Location1).OrderBy(l => l).ToArray();
}
}
private int[] LocationIDList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.locations.Select(lid => lid.idlocation).OrderBy(lid => lid).ToArray();
}
}
Here you can do thing, instead of taking two different array of name and id you can take list of station class like this.
private List<stations> StationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.OrderBy(s => s.Station1).ToList();
}
}
now assign this list to cbStation as datasource like this
cbStation.DataSource =StationNameList() ;
cbStation.DataTextField = "Station1";//it is text field that you want to display
cbStation.DataValueField = "idstations";//it is value field of combo box
cbStation.DataBind();
Now use SelectedValue property of conbobox instead of SelectedIndex property you will get
station id that related to station name.
TS.stationID = cbStation.SelectedValue;
Same thing is for location also
you can also use array instead list here.

A Problem in DataGridView : datagridview seems readonly to user (WinForms)

I have a datagridview in my form. It fills by selecting country with cities of country.I have set the property (AllowUsersToAddRow = True)
but when i run my project user can't add or edit or delete any row.I checked it.It is not readonly(readonly = false) and It is enable (Enabled = true)
What's the problem?
Code of fill datagridview:
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex>=0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
dgvValues.DataSource = from record in Program.dal.Cities(CountryId) select new { record.City};
}
If you find this question useful don't forgot to vote it.
To give a simplified example, if I do the equivalent of your query, such as:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
dataGridView.DataSource = cities;
I get the same result as you - no option to add new rows, but if I change to BindingList<T> and set this to AllowNew it all works:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
var citiesBinding = new BindingList<City>(cities);
citiesBinding.AllowNew = true;
dataGridView.DataSource = citiesBinding;
EDIT - with a solution for your particular example:
private class City
{
public string Name { get; set; }
}
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex >= 0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
var queryResults = from record in Program.dal.Cities(CountryId) select new City { Name = record.City };
var queryBinding = new BindingList<City>(queryResults.ToList());
queryBinding.AllowNew = true;
dgvValues.DataSource = queryBinding;
}
Note that a) I had to change the anonymous type in the query select into a concrete type City and also change the IEnumerable<T> returned by Linq query to an IList<T> compatible type to create the BindingList<T>. This should work, however :)

Categories

Resources