how to insert a combobox in c# linq from another table - linq

I tried this but it jumps to the error message
I think there is some thing wrong in the date and combo box entry from another table!!!!!!!!!!!!(The city here is Foreign Key data type is int)
Someone could help !!!
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
Employee employee =new Employee();
employee.FName=txtFName;
employee.LName=txtLName;
employee.DOB=DTPicker.value;
employee.city=ComboCity.selectedItem.ToString();
MyDB.Employees.InsertOnSubmit(employee);
MyDB.SubmitChanges();
txtFName.text="";
txtLastName.text="";
DTPicker.Value="";
ComboCity.text="";
MessageBox.Show("Record Entered")
}
catch
{
MessageBox.Show("Wrong Entry");
}
}
And Thanks

Related

How can I remove a column from my SQLite table with sqlite-net-pcl that comes with Xamarin Forms?

I have a table that was created with this C# code:
public class ViewHistory
{
[PrimaryKey]
public string YYMMDD { get; set; }
public int UtcNow { get; set; }
public int Assign { get; set; }
public int Learn { get; set; }
public int Practice { get; set; }
public int Quiz { get; set; }
}
and then
db2.CreateTable<ViewHistory>();
I would like to check if the Assign column exists and then remove the Assign column if it exists. So far the suggestions I have seen have all been either quite old or have suggested creating a new table and also don't include any check to see if it exists.
Now with the latest release of sqlite-net-pcl (1.5.2) is there any way I can drop a column? If not can someone recommend a way to do this that's just using the C# features that are available to me with the PCL or with SQL that I could execute.
I saw this on SO but it doesn't really help me:
Delete column from SQLite table
SQLite does not support ALTER TABLE x DROP COLUMN x so you need to create a new table and copy data.
You can do all this via a single multi-line SQL statement and execute it, but this will walk you though the steps using the ORM as much as possible:
Note: This assumes that your model has be updated and does not include that column anymore and your current database might or might not have it...
var conn = new SQLiteConnection(.....
conn.CreateTable<ViewHistory>();
~~~
if (0 < conn.ExecuteScalar<int>("SELECT COUNT(*) AS colcount FROM pragma_table_info('ViewHistory') WHERE name='Assign'"))
{
try
{
conn.BeginTransaction();
conn.Execute("ALTER TABLE ViewHistory RENAME TO backup;");
conn.CreateTable<ViewHistory>();
// Column map and copy data
var columns = conn.GetMapping<ViewHistory>(CreateFlags.None).Columns;
var columnNames = string.Join(",", columns.Select(p => p.Name));
conn.Execute($"INSERT INTO ViewHistory ({columnNames}) SELECT {columnNames} FROM backup;");
conn.Execute("DROP TABLE backup;");
conn.Commit();
conn.Execute("VACUUM");
}
catch (Exception ex)
{
conn.Rollback();
throw ex;
}
}
Note: Typically I just use "DB Browser for SQLite", make all the table/column alterations to the database and copy the "DB Log output" that contains all the SQL statements and paste that into a single SQLConnnection.Exceute statement...

DevExpress XRPictureBox ImageUrl

[Sorry for my bad english]
I made a report about a job applicant profiles where the path of the applicant photo stored in the database .
I tried the following code :
private void ApplicantForm_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
objectDataSource1.Fill();
// this.xrPictureBox1.ImageUrl = #"\\10.10.101.186\photo\" + Report.GetCurrentColumnValue("APPLICANT_PHOTO");
}
But all the photos that displayed was a picture of the first applicant.
Is there anything wrong with my code ?
You must put the code in the event BeforePrint of xrPictureBox1 :
private void xrPictureBox1_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
xrPictureBox1.ImageUrl = #"\\10.10.101.186\photo\" + Report.GetCurrentColumnValue("APPLICANT_PHOTO");
}

Editable Combobox

I have a singleton EmployeeDatabase that contains an ObservableList of employees.
This ObsList populates the contents of an editable combobox.
When a user selects one of the employees from the combo box and hits a button, I want that employee (from the database) to be displayed in a toString() in the console.
The problem is, the editable combobox does not let me select an employee directly. I'm supposed to use a StringConverter to turn that String into an Employee.
But the Employee already exists in the singleton database! Do I have to search for them in the database? Or is there an easier way to get the Employee as if the combobox weren't editable, and all I would have to do is cmbx.getSelectionModel().getSelectedItem()?
You don't need to go back to the database, since you already have an ObservableList which contains the Employees that are in there. You should be able to do something like:
final ComboBox<Employee> employeeCombo = new ComboBox<>();
employeeCombo.setItems(EmployeeDatabase.getInstance().getEmployees());
employeeCombo.setConverter(new StringConverter<Employee>() {
#Override
public Employee fromString(String string) {
for (Employee employee : employeeCombo.getItems()) {
if (string.equals(employee.getName())) { // may need more logic...
return employee ;
}
}
Employee employee = new Employee(string);
// if things are set up correctly, this call should both update the database
// and the observable list to which the combo box points
EmployeeDatabase.getInstance().add(employee);
return employee ;
}
#Override
public String toString(Employee employee) {
return employee == null : null ? employee.getName();
}
});
employeeCombo.setEditable(true);

WP7 delete item from listBox via message box

need some help, when i click the tap_event I get a message box delete or cancel which works and the price is taken off the total but it does'nt update the shopping cart after, it crashes on "ListBoxCart.Items.Remove(curr), thanks in advance!
private void listBoxCart_Tap(object sender, GestureEventArgs e)
{
if (MessageBox.Show("Are you sure!", "Delete", MessageBoxButton.OKCancel)
== MessageBoxResult.OK)
{
foreach (Dvd curr in thisapp.ShoppingCart)
{
if (curr.Equals(listBoxCart.SelectedItem))
{
listBoxCart.Items.Remove(curr);
listBoxCart.SelectedIndex = -1;
total -= Convert.ToDecimal(curr.price);
NavigationService.Navigate(new Uri("/ShoppingCart.xaml", UriKind.RelativeOrAbsolute));
}
}
txtBoxTotal.Text = total.ToString();
listBoxCart.ItemsSource = thisapp.ShoppingCart;
}
else
{
NavigationService.Navigate(new Uri("/ShoppingCart.xaml", UriKind.RelativeOrAbsolute));
}
}
I have wrote an artile (sorry in french but you can read the XAML) : http://www.peug.net/2012/05/17/contextmenu-dans-listbox-datatemplate/
and in the code-behind : an example :
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
var menuItem = sender as MenuItem;
var fe = VisualTreeHelper.GetParent(menuItem) as FrameworkElement;
Dvd _fig = fe.DataContext as Dvd;
thisapp.ShoppingCart.Remove(_fig);
reloading();
}
When you set the ItemsSource property for the ListBox, it generates a read-only collection and displays them. What you're trying to do is access this read-only collection and modify it but because it's read-only, you can't do that.
Instead you can either have your collection implement the INotifyCollectionChanged interface and raise a collection changed event when the user has deleted the item or use an ObservableCollection instead to store your items. ObservableCollection implements the INotifyCollectionChanged interface for you so you can remove items from the ObservableCollection and the changes will reflect in the Listbox automatically.
ObservableCollection also implements INotifyPropertyChanged so any property updates will also be updated in the ListBox.

Bind WPF DataGrid to LINQ Query (Entity Framework)

This must be very simple, but I seem to be missing something. I've searched around for a few hours without coming across anything that can resolve my problem. The issue is that although I can assign my LINQ query to a WPF DataGrid, when I try to edit one of the DataGrid's values I get the following error:
System.InvalidOperationException was unhandled
Message='EditItem' is not allowed for this view.
Source=PresentationFramework
StackTrace:
at System.Windows.Controls.ItemCollection.System.ComponentModel.IEditableCollectionView.EditItem(Object item)
at System.Windows.Controls.DataGrid.EditRowItem(Object rowItem)
at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoutedEventArgs e)
at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(Object sender, ExecutedRoutedEventArgs e)
at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
The XAML for my DataGrid looks like this:
<DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" Height="565" HorizontalAlignment="Left" Margin="6,92,0,0" Name="translatedStringsDataGrid1" RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" Width="602">
<DataGrid.Columns>
<DataGridTextColumn x:Name="stringsIDColumn2" Binding="{Binding Path=StringsID}" Header="Strings Name" Width="SizeToHeader" />
<DataGridTextColumn x:Name="translatedStringsValueColumn1" Binding="{Binding Path=TranslatedStringsValue}" Header="Translated Strings Value" Width="SizeToHeader" />
</DataGrid.Columns>
</DataGrid>
I am doing a LINQ query in the SelectedChange event of a ComboBox like this:
private void cbSelectLang_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var query = from o in _context.TranslatedStrings.Local
where o.LanguagesID == cbSelectLang.SelectedIndex + 1
join r in _context.Strings.Local on o.StringsID equals r.StringsID into SubSet2
from s in SubSet2.DefaultIfEmpty()
select new { StringsID = s.StringsName, TranslatedStringsValue = o.TranslatedStringsValue };
this.translatedStringsDataGrid1.ItemsSource = query;
}
I'm using "POCO entities" if anybody thinks there is an easier way of accomplishing this. I really do get the feeling that I'm missing something very basic and obvious, if anybody would be so kind as to point it out to me! :-)
Many thanks.
I haven't tested this, but I fairly sure your problem is because you're returning an anonymous type from your query. Try changing it to
...
from s in SubSet2.DefaultIfEmpty()
select new MyRealType
{
StringsID = s.StringsName,
TranslatedStringsValue = o.TranslatedStringsValue
};
where you need to define MyRealType.
Thanks partly to Phil I now have a workable technique which involves an ObservableCollection and a new holder type:
private class JoinClass
{
public string StringsID { get; set; }
public string TranslatedStringsValue { get; set; }
}
private void cbSelectLang_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ObservableCollection<JoinClass> collection = new ObservableCollection<JoinClass>();
var query = from o in _context.TranslatedStrings.Local
where o.LanguagesID == cbSelectLang.SelectedIndex + 1
join r in _context.Strings.Local on o.StringsID equals r.StringsID into SubSet
from s in SubSet.DefaultIfEmpty()
select new JoinClass { StringsID = s.StringsName, TranslatedStringsValue = o.TranslatedStringsValue };
foreach (var item in query)
{
collection.Add(item);
}
this.translatedStringsDataGrid1.ItemsSource = collection;
}
Thank you!

Resources