private void EmployeeContractAction_Execute(object sender, SimpleActionExecuteEventArgs e)
{
Employee detail;
PropertyCollectionSource em = (PropertyCollectionSource)((ListView)View).CollectionSource;
detail = (Employee)em.MasterObject;
ShowViewParameters svpInternal = new ShowViewParameters();
XPObjectSpace objSpaceNew = (XPObjectSpace)ObjectSpace.CreateNestedObjectSpace();
Employee objEmp = (Employee)objSpaceNew.GetObject(detail);
EmployeeContract objReg;
objReg = null;
if (objReg == null)
{
objReg = new EmployeeContract(objSpaceNew.Session);
}
objReg.Employee = objEmp;
svpInternal.CreatedView = Application.CreateDetailView(objSpaceNew, "EmployeeContract_DetailView2", true, objReg);
svpInternal.TargetWindow = TargetWindow.NewModalWindow;
svpInternal.Context = TemplateContext.View;
Application.ShowViewStrategy.ShowView(svpInternal, new ShowViewSource(null, null));
objReg.Save();
ObjectSpace.CommitChanges();
//View.ObjectSpace.Refresh();
}
I created this code, if I added new data it can't be saved, but if I edit existing data, it is will be changed. Can anyone help me?
Related
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.
I have section in my class that looks like this:
public Details GetTicketById(string #ref)
{
var query = "SELECT * FROM support WHERE ref = #ref";
var args = new Dictionary<string, object>
{
{"#ref", #ref}
};
DataTable dt = ExecuteRead(query, args);
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
var details = new Details
{
#ref = Convert.ToString(dt.Rows[0]["ref"]),
subject = Convert.ToString(dt.Rows[0]["subject"]),
contact_name = Convert.ToString(dt.Rows[0]["contact_name"]),
company_name = Convert.ToString(dt.Rows[0]["company_name"]),
description = Convert.ToString(dt.Rows[0]["description"]),
business_impact = Convert.ToString(dt.Rows[0]["business_impact"]),
severity = Convert.ToString(dt.Rows[0]["severity"])
};
return details;
}
I know that there is a return value when I debug.
My button in my main form looks like this:
private void Button3_Click(object sender, EventArgs e)
{
var getTicket = new ticket();
getTicket.GetTicketById("1235");
ticket.Details td = new ticket.Details();
td.#ref = txtRef.Text;
td.subject = txtSubject.Text;
td.contact_name = txtContact_Name.Text;
td.company_name = txtCompany_Name.Text;
td.description = rtDescription.Text;
td.business_impact = rtBusiness_Impact.Text;
td.severity = txtSeverity.Text;
}
Unfortunately my text boxes do not show the values from my returned data table.
Can you see why?
Your method GetTicketById() return value like you and see with debug. But you don't take this value into variable. Do this:
var details = getTicket.GetTicketById("1235");
In order to set Text property to new value do this:
txtSubject.Text = details.subject
txtContact_Name.Text = details.contact_name
txtCompany_Name.Text = details.company_name
// and so on
This line need to delete
ticket.Details td = new ticket.Details();
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()
I've been struggling for the past 3 days with removing or overwriting ListPicker values. I want the click event of a button to remove the old list items and populate it with the new ones. I use LINQ to parse values from an XML file. The problem is that no matter what I try I always get an exception such as "Operation not supported on read-only collection." etc. Is there a way to remove all the values from the ListPicker?
Here's the code:
public partial class Visa : PhoneApplicationPage
{
List<Tiedot> vastausLista = new List<Tiedot>();
XDocument lista = XDocument.Load("Faktat.xml");
Random rand = new Random();
int piste = 0;
int levelStart = 1;
string level = string.Empty;
// Constructor
public Visa()
{
InitializeComponent();
tbPisteet.Text = string.Format("{0}/25", piste.ToString());
level = string.Format("level{0}", levelStart.ToString());
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (levelStart <= 1)
{
var documents =
(from docs in lista.Descendants("Taso")
where docs.Attribute("id").Value == level
select new
{
Elain = docs.Elements("vaihtoehto")
}).ToList();
foreach (var doc in documents)
{
foreach (var section in doc.Elain)
{
foreach (var item in section.Elements("vastaus"))
{
vastausLista.Add(new Tiedot { Elain = item.Value });
}
}
}
vaihtoehtoLista.ItemsSource = vastausLista;
var kuvaKysymys = (from tiedot in lista.Descendants("Taso")
where tiedot.Attribute("id").Value == level
select new Tiedot
{
Kuva = (string)tiedot.Element("kuva").Value,
Question = (string)tiedot.Element("kysymys").Value
}).FirstOrDefault();
BitmapImage kuvaKuva = new BitmapImage();
kuvaKuva.UriSource = new Uri(kuvaKysymys.Kuva, UriKind.Relative);
image.Source = kuvaKuva;
tbQuestion.Text = kuvaKysymys.Question;
}
base.OnNavigatedTo(e);
}
private void vaihtoehtoLista_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (vaihtoehtoLista.SelectedIndex == 1)
{
Update();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
UpdateLevel();
}
public void Update()
{
piste++;
tbPisteet.Text = string.Format("{0}/25", piste.ToString());
MessageBox.Show("You're correct!!");
}
public void RemoveOldLevel()
{
while (vastausLista.Count > 0)
vaihtoehtoLista.Items.Remove(vastausLista[0]);
}
public void UpdateLevel()
{
levelStart++;
level = string.Format("level{0}", levelStart.ToString());
var documents =
(from docs in lista.Descendants("Taso")
where docs.Attribute("id").Value == level
select new
{
Elain = docs.Elements("vaihtoehto")
}).ToList();
foreach (var doc in documents)
{
foreach (var section in doc.Elain)
{
foreach (var item in section.Elements("vastaus"))
{
vastausLista.Add(new Tiedot { Elain = item.Value });
}
}
}
RemoveOldLevel();
vaihtoehtoLista.ItemsSource = vastausLista;
var kuvaKysymys = (from tiedot in lista.Descendants("Taso")
where tiedot.Attribute("id").Value == level
select new Tiedot
{
Kuva = (string)tiedot.Element("kuva").Value,
Question = (string)tiedot.Element("kysymys").Value
}).FirstOrDefault();
BitmapImage kuvaKuva = new BitmapImage();
kuvaKuva.UriSource = new Uri(kuvaKysymys.Kuva, UriKind.Relative);
image.Source = kuvaKuva;
tbQuestion.Text = kuvaKysymys.Question;
}
}
You have to use an ObservableCollection with your elements inside, as the DataContext of your ListPicker. Something like this:
ListPicker picker = new ListPicker();
ObservableCollection<Object> coll = your items inside;
picker.DataContext = coll;
And after you can modify directly the ObservableCollection. Or you can use:
ListPicker picker = new ListPicker();
picker.ItemsSource = List<> with your items;
But you have to reset the ItemSource each time you change the content of your List<>.
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 :)