There is a DataGridView in my form, and I have a save button. Both the DataAdapter and the DataSet are automatically generated.
I want to use DataAdapter.Update() to update my database, but it seems nothing changed after I updated the DataGridView when I open the table in .mdf or generate the solution again.
I knew this was asked and read some posts, trying to find the solutions but it doesn't work.
I have set the .mdf file property 'Copy to output directory' to 'Copy if newer'
BindingSource and BindingNavigator work successfully.
Code Sample
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.myTableTableAdapter.Fill(this.myDatabaseDataSet.myTable);
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(myTableTableAdapter.Adapter);
myTableTableAdapter.Adapter.InsertCommand = sqlCommandBuilder.GetInsertCommand();
myTableTableAdapter.Adapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand();
myTableTableAdapter.Adapter.UpdateCommand = sqlCommandBuilder.GetUpdateCommand();
}
private void SaveSToolStripButton_Click(object sender, EventArgs e)
{
try
{
bindingSource1.EndEdit();
myTableTableAdapter.Adapter.Update(myDatabaseDataSet.myTable);
MessageBox.Show("Succeed");
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Failed");
}
}
}
}
Just solved this problem. Someone with the same problem may refer to this.
Why saving changes to a database fails? Steve's answer is quite helpful to understand this problem.
I did modify my database, but when I connect the datasource, it just copy again, so it seems the update fails.
You can write the connection manually, changing the |Directory| to where your database actually is. Or do something like this:
string dataDir = AppDomain.CurrentDomain.BaseDirectory;
if (dataDir.EndsWith(#"\bin\Debug\")
|| dataDir.EndsWith(#"\bin\Release\"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}
But I don't recommend this because it may modify your original database when you're debugging. It should be only modifying my database in the bin folder while keeping the original database intact.
What you have to do is just setting your .mdf file Copy to directory property to Copy if newer or Copy Never (In this case, add a script to copy the file to the bin\debug folder only if it doesn't exist). And do not focus too much on your original .mdf in your Resource Manager.
And other notes:
Lines like myTableTableAdapter.Adapter.UpdateCommand = sqlCommandBuilder.GetUpdateCommand(); are not necessary.
When associated with a DataAdapter, the DbCommandBuilder automatically generates the InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter if they are null references. If a Command already exists for a property, the existing Command is used.
MSDN
I need to check before calling BindingSource.EndEdit()
this.Validate();
Related
Trying to debug an application that is opened by opening a text-file associated to open the application being debugged.
Is there a way to start the debug and wait for the application to be called without the "Start external program" start action?
Ultimately I'm trying to get the file information of the text-file that opens the application, so that it can be used in the application as a "saved project" file.
I have a text-file named "myFile.cats", I've associated this file extension to open with my executable solution made by the visual studio application in the debug bin.
I've tried using the StartupEventArgs, but it doesn't come back with anything obviously since it's not being called from an external file. So I don't seem to have a way of testing this to make sure it works...
Any help would be greatly appreciated.
using Caliburn.Micro;
using ApplicationWPFUI.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using ApplicationLibrary;
namespace ApplicationWPFUI
{
public class Bootstrapper : BootstrapperBase
{
public Bootstrapper()
{
Initialize();
}
//myFile.cats File opens this exe and the 'OnStartup' runs, where is the myFile.cats information being passed in?
protected override void OnStartup(object sender, StartupEventArgs e)
{
if (e.Args.Count() != 0)
{
//Save the startupEventArgs to a variable
GlobalConfigs.FileList.Files = e.Args.ToList();
}
DisplayRootViewFor<MainViewModel>();
}
}
}
I was doing it correctly already, with one slight change that needed to be made.
The information needed for the file that opens the application is in the GlobalConfigs.FileList.Files = e.Args.ToList();. But, I only need the first variable in that list.
So calling the following does the trick:
GlobalConfigs.FileList.Files = e.Args[0].ToString();
Obviously, the StartupEventArgs will not always have information in there, since I'll be calling the application by itself as well as opening it with associated files. So I just wrapped that in an if statement:
if (e.Args.Count() != 0) {
GlobalConfigs.FileList.File = e.Args[0].ToString();
}
And Bobs your uncle.
I'm developing a POS in WPF.
For CRUD operations, I'm using Entity Framework.
Created a WPF View ProductADD
Product Add View Snap
Created a Class ProductController in Controller Folder
Made object of Entity Framework in ProductController Class ProductController Calss Snap
Created a method: SaveProduct(Product product) which is taking product object as argument and saving it to database using EF.
And From Xaml.Cs I'm calling ProductController Class's Saveproduct method and sending the new product data to it.
private void Button_Click(object sender, RoutedEventArgs e)
{
ProductController pc = new ProductController();
PRODUCT product = new PRODUCT();
product.PRODUCT_NAME = Product_Name.Text.ToString();
product.UNITPRICE = Convert.ToInt32(Unit_Price.Text.ToString());
product.CATEGORY_Id = 1;
pc.SaveProduct(product);
MessageBox.Show("Product Added Successfully");
this.Close();
}
And in ProductController the following code is updating the database
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PizzaLounge.Models;
namespace PizzaLounge.Controllers
{
public class ProductController
{
PizzaLoungeEntities db = new PizzaLoungeEntities();
public void SaveProduct(PRODUCT product)
{
db.PRODUCTs.Add(product);
db.SaveChanges();
}
}
}
The code executes successfully but it doesn't save the product in database. P.S. I have used db.savechanges().
Am I missing something or using wrong approach to update database?
You are probably using |DataDirectory| in your connection string. If debugging in Visual Studio, the database you are using is in the bin/debug folder.
Unfortunately if you look at the db through Server Explorer it has a different connection string so you don't see the changes.
Also if the database property "Copy to Output directory" is set to Copy Always then every time you debug you will overwrite your db and you won't see the data you added. You can check if this is happening by using a new db context in the same debug session where you add the records. If the new context can get the records from the db then you know they must be being written (as well as the other checks listed in the comments)
This can be fixed by changing Copy To Output Directory to Never Copy or Copy If Newer.
Because you are using mdf file attached to your project so your problem is like this question
Attaching database to my project
You are saving data to database that is in bin\debug folders ,and then you see the mdf file that is in your project folder and you don't see the data .
change your connection string from DataDirectory to
absolute path to the project database file. When deploying, just change it back to |DataDirectory|
How did you checked that the products haven't been added, from db.PRODUCTs or from the Database Explorer?
Maybe you just need to dispose your context, change your ProductController for something like:
using(var db = new PizzaLoungeEntities()){
db.PRODUCTs.Add(product);
db.SaveChanges();
}
Or to dispose ProductController after you finish to use it.
Hi,
I am having Could not load type error when I release my code into live environment. If I remove the code Inherits="CheckIEBrowser.Check" that gets rid of the error, it displays the page, but it doesn't work as it should.
Thanks in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CheckIEBrowser
{
public partial class Check : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
...
Make a copy of Check.aspx and its CS fle to your local
Delete Check.aspx and Check.aspx.cs manually from directory
Clean Solution
Right click your solution add new form and name it as Check.aspx
Copy your local saved check.aspx contents to Check.aspx that we created newly (except line 1 )
do the same for check.aspx.cs also
rebuild your solution
Than try
if its not work, delete CheckIEBrowser.sln file and try
I am pretty new to coding ADO.Net/entity framework stuff. I am trying to follow "Microsoft ADO.NET Entity Framework Step by Step", Microsoft Press Mueller. I'm using VS 2012 with EF6 installed.
Start a new project, and adding an new Empty ADO.NET Entity Data Model. It's pretty simple, a few scalars and one Enumeration called UserFavorites. Then add a data source > Object > Drilling down to my UserFavorites object and finishing. I change toe UserFavorites object on the data source tab to detail view ( and a couple other changes like combo box and label on the others). Then drag the UserFavorites object to the form. It creates a Binding source and binding navigator all as it should. After enabling the save button and entering the code below it runs great and gets the records from the database that can be scrolled between. The problem is when I click the plus to add a record, fill it in, and click save, I get validation errors. on the
Hide Copy Code
UserFavoritesContext.SaveChanges();
line. The first error is
"Exception:Thrown: "Value of '1/1/0001 12:00:00 AM' is not valid for 'Value'. 'Value' should be between 'MinDate' and 'MaxDate'." (System.ArgumentOutOfRangeException)"
There is a date picker on the form, and it's filled out correctly. If I remove that item from my model I get errors on the next item in the model. For some reason it's not pulling the data filled in on the form and trying to use defaults (or null).
I can't find anyone else with this problem online, so I guess I am missing something silly. I followed the book exactly ( and can't find a help forum for the book). I hope this is clear enough for someone to offer some guidance.
Images of Form and Data Source,Model,Error, and zip of project are at
https://www.dropbox.com/sh/z6yhvbp1uk7bobm/AADa7fnS82PzwNLlPrycnCYza?dl=0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserFavoritesEF6
{
public partial class Form1 : Form
{
// Define the context used to access the database.
UserFavoritesModelContainer UserFavoritesContext;
<pre>
public Form1()
{
InitializeComponent();
// Initialize the database context.
UserFavoritesContext = new UserFavoritesModelContainer();
// Query the database for the records you want.
var dbQuery =
UserFavoritesContext.UserFavorites.Where(id => id.UserId >= 0).ToArray();
}
private void userFavoritesBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
UserFavoritesContext.SaveChanges();
}
private void Form1_Load(object sender, EventArgs e)
{
// Assign a local copy of the queried records to the
// binding source.
userFavoritesBindingSource.DataSource =
UserFavoritesContext.UserFavorites.Local;
// Fill the Favorite Colors list with acceptable colors and
// choose a default.
favoriteColorComboBox.DataSource = Enum.GetValues(typeof(ColorNames));
favoriteColorComboBox.SelectedItem = ColorNames.Red;
}
}
}
I'm learning about ADO.Net entity framework, and
I'm stuck at adding entity table object to the database.
I have a local database in solution called testDB.
It has two columns - id(primary, unique, identiy),name(varchar(100))
and entity for it. The main application code is here below.
Problem is, that using this code it doesn't add anything to the table, but also
I'm not having any errors.
What could go wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace entityproject
{
class Program
{
static void Main(string[] args)
{
String someString;
someString = "Just a test";
testDBEntities tdbEntity = new testDBEntities();
test tblTest = new test();
tblTest.name = someString;
tdbEntity.test.Add(tblTest);
tdbEntity.SaveChanges();
}
}
}
App.config here
http://pastie.org/6980938
I think I know the problem - had the same thing last time I tried using SQL CE.
The connection string doesn't point to the sdf file that you created - it uses a new one that I believe gets put into your bin\Debug or bin\Release directory (in your config file as data source=|DataDirectory|\testDB.sdf), with your EXE and DLLs. If you check that directory, I bet you'll find another sdf file there, that has a bunch of records added.
If you want to use the sdf that you've already created, change the connection string to point specifically to that file.