using a method from viewmodel on a buttonclick event in view - c#

I'm new to mvvm and I'm trying use a method "SaveAll"that saves the observablecollection to the database and I want to call it from a buttonclick event in code behind the view, but it doesn't seem to be possible.
This is the code I have so far. The error happens in NetworkViewModel.SaveAll(person)
namespace MyProject
{
using Model;
public class NetworkViewModel : INotifyPropertyChanged
{
private ObservableCollection<Person> _networkList1 = new ObservableCollection<Person>();
public ObservableCollection<Person> NetworkList1
{
get { return _networkList1; }
set { _networkList1 = value; RaisePropertyChanged("NetworkList1"); }
}
public NetworkViewModel()
{ }
public void SaveAll(Person person)
{
String dbConnectionString = #"Data Source =movieprepper.sqlite;";
SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
sqliteCon.Open();
var transaction = sqliteCon.BeginTransaction();
String DeleteQuery = "delete from networking";
SQLiteCommand DeleteCommand = new SQLiteCommand(DeleteQuery, sqliteCon);
DeleteCommand.ExecuteNonQuery();
foreach (Person p in _networkList1)
{
String Query = "insert into networking (firstname, lastname) values ('" + p.FirstName + "','" + p.LastName + "')";
SQLiteCommand Command = new SQLiteCommand(Query, sqliteCon);
Command.ExecuteNonQuery();
}
transaction.Commit();
sqliteCon.Close();
}
}
}
and in the code behind view I got this
namespace MyProject
{
public partial class Networking : Window
{
public Networking()
{
InitializeComponent();
this.DataContext = new NetworkViewModel();
}
private void btn_save_network_Click(object sender, RoutedEventArgs e)
{
NetworkViewModel.SaveAll(Person);// This is where error occurs
}
}
}
This doesn't seem to work I keep getting
"an object reference is required for the non static field, method or property"
I'm new to all this and trying to figure things out as I go but it seems I can't find the answer to this particular situation.

As mentioned, you should follow the command pattern for this. You can do so by updating your view model like this:
public class NetworkViewModel : INotifyPropertyChanged, ICommand
{
private ObservableCollection<Person> _networkList1 = new ObservableCollection<Person>();
public event EventHandler CanExecuteChanged;
public ObservableCollection<Person> NetworkList1
{
get { return _networkList1; }
set { _networkList1 = value; RaisePropertyChanged("NetworkList1"); }
}
public NetworkViewModel()
{ }
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
String dbConnectionString = #"Data Source =movieprepper.sqlite;";
SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
sqliteCon.Open();
var transaction = sqliteCon.BeginTransaction();
String DeleteQuery = "delete from networking";
SQLiteCommand DeleteCommand = new SQLiteCommand(DeleteQuery, sqliteCon);
DeleteCommand.ExecuteNonQuery();
foreach (Person p in _networkList1)
{
String Query = "insert into networking (firstname, lastname) values ('" + p.FirstName + "','" + p.LastName + "')";
SQLiteCommand Command = new SQLiteCommand(Query, sqliteCon);
Command.ExecuteNonQuery();
}
transaction.Commit();
sqliteCon.Close();
}
}
Since your SaveAll method did not actually use the Person (you loop over all of them in your collection instead), I wouldnt pass the People parameter along.
Then, instead of having your code behind invoke the method. You can bind your button to the view model. Your XAML would look like this:
<Button x:Name="SavButton"
Command="{Binding }"
Content="Save All People" />
If you wanted to save a specific person that you have selected, you can pass them along in your binding too
<Button x:Name="SavButton"
Command="{Binding }"
CommandParameter="{Binding Path=SelectedPerson}"
Content="Save All People" />
public void Execute(object person)
{
People p = (People)person;
// save......
}
That is assuming you have data bound the selected person to a property on your view model called SelectedPerson.
Hope this helps.

The technical correct answer would be that NetworkViewModel is a class name, you need a class instance to call your method on. For example the one you put into your DataContext earlier.
((NetworkViewModel)this.DataContext).SaveAll(Person);
But it would be better to read a about the command pattern that Microsoft wants you to use with WPF. It works a lot better with MVVM than your code behind.

Related

using same form for insert and edit without having unused variables in c#

ok guys/girls, i am new to programming and have a question. i created one winform for insert data into sql server..now i want to use that same form to update data..i already did that with constructor overload and chaining, and it is work!
on main form frmEmployees i have two buttons, btnAddEmployee and btnUpdateEmployee, i also have employeeID (i get id from the datagrid) and a bool variable called 'isEditMode =true', now when i click btnUpdateEmployee i am sending EmployeeID, and isEditMode values to overloaded constructor..and frmAddEmployee opens..there i have global private variabables employeeID and bool isEditmode..and then i set their values via overloaded constructor, and that is work, BUT..when i click btnAddEmployee i am not sending employeeID and isEditMode values..and i come up with unused variables when adding employee..
private int employeeID;
private bool isEditMode;
public frmAddEmployee()
{
InitializeComponent();
this.AutoValidate = AutoValidate.Disable;
}
public frmAddEmployee(int employeeID, bool isEditMode): this()
{
this.employeeID = employeeID;
this.isEditMode = isEditMode;
}
You haven't showed us a lot of code but i will give you good example of how i am handing communication between program and SQL Database.
So first of all I create class for each object. In your example i see you have Employee so i would create class with few information (variables) about each of my employee and functions i want to have for them. So class would look something like this:
public class Employee
{
static string databaseString = "";
public int Id { get { return _Id; } } //This is property
public string Name { get { return _Name; } set { _Name = value; } } //This is property
private int _Id; //This is private variable used by property
private string _Name; //This is private variable used by property
public Employee()
{
//Constructor used to create empty object
}
public Employee(int Id)
{
try
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT NAME FROM Employee WHERE ID = #ID", con))
{
cmd.Parameters.AddWithValue("#ID", Id);
SqlDataReader dr = cmd.ExecuteReader();
//I am usin IF(dr.Read()) instead of WHILE(dr.Read()) since i want to read only first row.
if (dr.Read())
{
this._Id = Id;
this._Name = dr[0].ToString();
}
else
{
System.Windows.Forms.MessageBox.Show("There was no Employee with that ID in database!");
}
}
}
}
catch(SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
public void Save(bool showMessage)
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE Employee SET NAME = #N WHERE ID = #ID", con))
{
cmd.Parameters.AddWithValue("#N", this._Name);
cmd.Parameters.AddWithValue("#ID", this._Id);
cmd.ExecuteNonQuery();
if (showMessage)
System.Windows.Forms.MessageBox.Show("Employee saved!");
}
}
}
public static void Create(string Name, bool showMessage = true)
{
using (SqlConnection con = new SqlConnection(databaseString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Employee (ID, NAME) VALUES (COALESCE(MAX(ID), 1), #NAME)", con))
{
cmd.ExecuteNonQuery();
if (showMessage)
System.Windows.Forms.MessageBox.Show("New Employee created!");
}
}
}
}
Now when i have my class i can call it 2 ways:
Employee emp = new Employee(); //This will create empty employee object
Employee emp1 = new Employee(1); //This will create employee object and will load employees data from database where employees id == 1
Also what i can do is:
Employee.Create("SomeName"); //Calling public static method from Employee class. Doesn't require you to create object for static methods
or if i have loaded employee and want to change it's name and then save i would do it like this:
Employee emp2 = new Employee(1); //Created and loaded emp from database
emp2.Name = "Changed Name";
emp2.Save(); //Called public method.
So now if you have form which display one employee it would look like this:
public partial class Form1 : Form
{
private Employee emp;
public Form(int EmployeeID)
{
InitializeComponents();
//Creating new object of Employee but with constructor that will automatically load variables into it.
emp = new Employee(EmployeeID);
//Checking to see if employee is loaded since if there was no employee with given ID it would return null
if(emp.Id == null || < 1)
{
DialogResult dr = MessageBox.Show("Employee doesn't exist. Do you want to create new one?", "Confirm", MessageBoxButtons.YesNo);
if(dr == DialogResult.No)
{
//User doesn't want to create new employee but since there is no employee loaded we close form
this.Close();
}
else
{
Employee.Create("New Employee");
MessageBox.Show("New employee created");
//Here we need to load this employee with code like emp = new Employee(newEmployeeId);
//To get new employee id you have 2 options. First is to create function inside Employee class that will Select MAX(ID) from Employee and return it. (bad solution)
//Second solution is to return value upon creating new employee so instead function `public static void Create()` you need to have `public static int Create()` so it returns newly created ID of new row in SQL database. I won't explain it since you are new and it will be too much information for now. You will easily improve code later. For now you can use Select Max(id) method
}
}
textBox1.Text = emp.Id;
textBox2.Text = emp.Name;
}
private void OnButton_Save_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Do you really want to save changes?", "Save", MessageBoxButtons.YesNo);
if(dr == DialogResult.Yes)
{
emp.Save();
}
else
{
//Here create private Reload function inside form that will do emp = Employee(emp.Id) and then set UI again.
}
}
private void OnButton_CreateNewEmployee_Click(object sender, EventArgs e)
{
Employee.Create("New Employee");
int newEmpID = something; //As i said up create method to select MAX ID or update SQL inside Create function to return newly created ID
//I am using using since after form closes it automatically disposes it
using(Form1 f = new Form1(newEmpID))
{
f.showDialog()
}
this.Close();
}
}

Reading Data from database and storing the data in a List

I'm reading some data from a database (information on properties) and i store the information in Property objects. I put the objects in a list of type Property and i display the contents of the list in a listbox. However instead of getting different data for each object I'm getting the same data multiple times. Ps. I instantiate the Property object inside the while loop and the issue persists.
void fillListBoxWithProperties()
{
List<Property> propList = new List<Property>();
db_connection();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "select * from property ";
cmd.Connection = connect;
MySqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
Property prop = new Property();
prop.PropId = Convert.ToInt32(dr["propertyId"]);
prop.Address = dr["Address"].ToString();
prop.PropType = dr["PropertyType"].ToString();
propList.Add(prop);
}
foreach(Property details in propList)
{
lstBoxProperties.Items.Add(String.Format("{0} {1}", details.PropId, details.Address));
}
}
What the list box prints
If i add this code to the loop just for testing:
Property prop = new Property();
prop.PropId = Convert.ToInt32(dr["propertyId"]);
prop.Address = dr["Address"].ToString();
prop.PropType = dr["PropertyType"].ToString();
propList.Add(prop);
//added code
foreach (Property o in propList)
{
Console.WriteLine(o.toString());
}
The result in the console is the following:
Ballyare,
Rathmulan,
Rathmulan,
Letterkenny,
Letterkenny,
Letterkenny,
Convoy,
Convoy,
Convoy,
Convoy,
Gweedore,
Gweedore,
Gweedore,
Gweedore,
Gweedore,
Glenties,
Glenties,
Glenties,
Glenties,
Glenties,
Glenties,
Property Class Code:
class Property
{
private static int _propId =0;
private static string _address="";
private static string _propType="";
public Property()
{
}
public int PropId
{
get { return _propId; }
set { _propId = value; }
}
public string Address
{
get { return _address; }
set { _address = value; }
}
public string PropType
{
get { return _propType; }
set { _propType = value; }
}
}
Well, now after you added the Property class, it's quite clear why all of your instances seem to have the same content. You made your private members holding the data static. So they don't exist separately for each instance but only once for all instances of the class. Remove the static keyword (and see some introduction for what it does)

In MVVM Light need to do logic for Pressing a button to generate a Database

I'm fairly new to MVVM Light for WPF. I'm using VIsual Studio 2013 and have created a project using C#. I've got the logic for a button in xaml. When the user clicks this button I would like for the app to generate a database and a datatable. I've got the binding command in the xaml which will fire of the relay command. I've also got a method in the model to generate the database and datatable. I've created a relay command in the view model but outside of that I'm not quite sure what to do next. Any help would be appreciated.
View - xaml
<Button Content="New Project" Margin="0,0,3,0" Command="{Binding AddProjectCommand}" IsEnabled="{Binding CommNotStreaming}" Grid.Column="2" Grid.Row="0"/>
View Model -
public class ProjectConfigViewModel : ViewModelBase
{
//Binding AddProjectCommand
public RelayCommand AddProjectCommand { get; set; }
private string consoleText { get; set; }
private StringBuilder consoleBuilder = new StringBuilder(360);
public ProjectConfigViewModel()
{
this.AddProjectCommand = new RelayCommand(this.AddProject);
}
public void AddProject()
{
//Not really sure what to do here to call the ProjectDbInteraction class
}
}
Model - Database Interaction class
public class ProjectDbInteraction
{
//String rawDBConnectionString = "Server=localhost; Database=12_rse_002_db; uid=root; pwd=password; Connection Timeout=5;"; //TODO Either pick a standard for make this edittable
public void CreateProjectDb(string projName)
{
try
{
MySqlConnection connection = new MySqlConnection("DataSource=localhost;UserId=root;pwd=password");
MySqlCommand command = new MySqlCommand("CREATE DATABASE " + projName + ";", connection);
connection.Open();
command.CommandText = "DROP DATABASE IF EXISTS " + projName;
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE Projects(ProjectID INT NOT NULL, ProjectName VARCHAR(VARCHAR(255), ProjectStartDate DateTime, ProjectEndDate DateTime, ProjectNotes VARCHAR(MAX) PRIMARY KEY (ProjectID))";
command.ExecuteNonQuery();
//command.CommandText = "CREATE TABLE Metabolites(MetaboliteID VARCHAR(10) NOT NULL, Metabolite_Name VARCHAR(45) NULL, ReactionTime INT NULL, PRIMARY KEY (MetaboliteID)";
connection.Close();
}
catch (Exception)
{
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Start by replacing
this.AddProjectCommand = new RelayCommand(this.AddProject);
with
this.AddProjectCommand=new RelayCommand(() => AddProject());
.
Then in your AddProject() method , that calls your database creation, something like:
ProjectDbInteraction.CreateProjectDb("some name");

SelectedItem only updates first row in database in WPF

I am developing an application to allow a user to enter their employee details of their company into a database. So far I am experimenting with WPF and trying to implement MVVM within my application while using Entity Framework.
I'm creating a Master-Detail application, and have been researching into how to achieve this using MVVM, as I'm very much new to it all.
One of the ways in which I have tried is by creating a property within my View-Model called SelectedEmployee and then binding it to a List View in my xaml, like so;
public Employee _SelectedEmployee;
public Employee SelectedEmployee
{
get
{
return _SelectedEmployee;
}
set
{
if (_SelectedEmployee == value)
return;
_SelectedEmployee = value;
OnPropertyChanged("SelectedEmployee");
}
}
<ListView HorizontalAlignment="Left" Name="listview" VerticalAlignment="Bottom" ScrollViewer.HorizontalScrollBarVisibility="Visible"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding LoadEmployee}" SelectionMode="Single" SelectedItem="{Binding SelectedEmployee, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="150" Grid.Row="1">
I then have a method that allows the user to update a SelectedItem within the List View. But this is where the problem occurs. When I select an item from the List View, it only updates the first row from the database and not the row I wanted to select.
Here's the method;
public void UpdateEmployee(Employee emp)
{
using (DBEntities context = new DBEntities())
{
emp = context.Employees.Where(e => e.EmployeeID == SelectedEmployee.EmployeeID).FirstOrDefault();
emp.Title = Title;
emp.FirstName = FirstName;
emp.Surname = Surname;
emp.Position = Position;
emp.DateOfBirth = DateOfBirth;
emp.Address = Address;
emp.Country = Country;
emp.Postcode = Postcode;
emp.PhoneNumber = PhoneNumber;
emp.MobileNumber = MobileNumber;
emp.FaxNumber = FaxNumber;
emp.Email = Email;
emp.NINumber = NINumber;
emp.ChargableResource = ChargableResource;
emp.ChargeOutRate = ChargeOutRate;
emp.TimeSheetRequired = TimeSheetRequired;
emp.WorkShift = WorkShift;
emp.BenefitsProvided = BenefitsProvided;
context.Employees.ApplyCurrentValues(emp);
context.SaveChanges();
}
}
I have bound my properties within my view model to the text-boxes within my xaml and then implementing OnPropertyChanged.
I am also using Commands to limit the amount of code-behind as its important for testability and maintainability.
Here is the command method to update;
private ICommand showUpdateCommand;
public ICommand ShowUpdateCommand
{
get
{
if (showUpdateCommand == null)
{
showUpdateCommand = new RelayCommand(this.UpdateFormExecute, this.UpdateFormCanExecute);
}
return showUpdateCommand;
}
}
private bool UpdateFormCanExecute()
{
return !string.IsNullOrEmpty(FirstName) ...
}
private void UpdateFormExecute()
{
UpdateOrganisationTypeDetail();
}
As I am new to MVVM, I'm not quite sure what I am doing wrong so would appreciate some input please :).
Then perhaps the problem is with your updating. I don't really understand what your trying to do with listview, but since it's not working in a simple datagrid this might help. it's not so much an answer as something that I wrote to find your error that happens not to contain your error. please do comment if anything is awry.
public partial class MainWindow : Window
{
private static MainViewModel _mainViewModel = new MainViewModel();
public static ObservableCollection<Employee> staff = new ObservableCollection<Employee>();
public MainWindow()
{
InitializeComponent();
this.DataContext = _mainViewModel;
dataGrid1.DataContext = staff;
listview.DataContext = staff;
Employee Employee1 = new Employee();
Employee1.name = "Jeff";
staff.Add(Employee1);
Employee Employee2 = new Employee();
Employee2.name = "Jefferson";
staff.Add(Employee2);
Employee2.name = "Tim";
}
}
public class Employee
{
public string name { get; set; }
}
public class MainViewModel : INotifyPropertyChanged
{
private string _SelectedEmployee;
public string SelectedEmployee
{
get { return _SelectedEmployee; }
set
{
_SelectedEmployee = value;
NotifyPropertyChanged("SelectedEmployee");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

c# property won't work?

hello guys i have a form... and i set my properties if the user will click the submit button and after then i will call my add_data function which contains my database query...but the problem is the properties I've set in my form will become empty in my add_data function...why this is happening?
actually i already try adding a messagebox in my form which contains the data in my properties after setting my properties value and it works fine but when i add it to my databasecon class the messagebox shows null... i try also putting my properties and database query function in the same class and it's working but what i want is to separate my properties and my database query functions...
this is the codes in my properties
class persons
{
//person attributes
private string fname;
private string lname;
private string age;
private string gnder;
private string address;
//initialize
public persons()
{
this.fname = "";
this.lname = "";
this.age = "";
this.gnder = "";
this.address = "";
}
//set and get properties
public string p_fname
{
get { return this.fname; }
set { this.fname = value; }
}
public string p_lname
{
get { return this.lname; }
set { this.lname = value; }
}
public string p_age
{
get { return this.age; }
set { this.age = value; }
}
public string p_gender
{
get { return this.gnder; }
set { this.gnder = value; }
}
public string p_address
{
get { return this.address; }
set { this.address = value; }
}
}
this is the codes in my form
public partial class add : Form
{
persons p = new persons();
databasecon d = new databasecon();
private void addbtn_Click(object sender, EventArgs e)
{
p.p_fname = this.fname.Text;
p.p_lname = this.lname.Text;
p.p_age = this.age.Text;
p.p_gender = this.gender.Text;
p.p_address = this.address.Text;
d.add_data();
this.Close();
}
}
and this is the codes in my database connection and queries
class databasecon
{
OleDbConnection con = new OleDbConnection();
persons p = new persons();
public databasecon()
{
con.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=../dbsample.mdb";
}
public void add_data()
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO person(u_fname,u_lname,u_age,u_gender,u_address)VALUES('" + p.p_fname + "','" + p.p_lname + "','" + p.p_age + "','" + p.p_gender + "','" + p.p_address + "')";
cmd.Parameters.AddWithValue("u_fname", p.p_fname);
cmd.Parameters.AddWithValue("u_lname", p.p_lname);
cmd.Parameters.AddWithValue("u_age", p.p_age);
cmd.Parameters.AddWithValue("u_gender", p.p_gender);
cmd.Parameters.AddWithValue("u_address", p.p_address);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show("Error : " + e);
}
finally
{
con.Close();
MessageBox.Show("New person has been successfully added.");
}
}
}
You need to pass p as a parameter to the add_data method.
public void add_data(persons person)
then call it with the parameter:
d.add_data(p);
and use the properties of person in the method:
cmd.Parameters.AddWithValue("u_fname", person.p_fname);
cmd.Parameters.AddWithValue("u_lname", person.p_lname);
cmd.Parameters.AddWithValue("u_age", person.p_age);
cmd.Parameters.AddWithValue("u_gender", person.p_gender);
cmd.Parameters.AddWithValue("u_address", person.p_address);
you create databasecon() in form and then call add_data method and you don't pass 'persons' instance. in databasecon you use persons istnace which is field in this class. you soudl add parameter do add_data method and pass instance or 'persons' you want to save and use it in command
Your p fields in your add and databasecon classes are separate. When you call d.add_data(), the d object can only see its instance of persons p ....
To fix this, pass the persons object into the add_data method.
class databasecon{
// Remove this line, we pass it into the function below
/* persons p = new persons(); */
public void add_data(persons p){
try{
// same code as before
}catch(Exception e){
// same code
}
finally{
// same
}
}
}
You have an instance of Person class which you fill and then use an instance of databasecon which is completely not conntected to the person class you filled.
Change add_data() to
public void add_data(person p) { ... }
this will use the properties from p passed as parameter.
You call it like this
d.add_data(p);
Except for that have a look at some C# for begginers book.
Overlooking the fact that your code is extremely poorly written.
You are not passing in the persons class that you created.
Something like
public void add_data(persons p) {//..blah}
Then
private void addbtn_Click(object sender, EventArgs e) {
p.p_fname = this.fname.Text;
p.p_lname = this.lname.Text;
p.p_age = this.age.Text;
p.p_gender = this.gender.Text;
p.p_address = this.address.Text;
d.add_data(p);
this.Close();
}
From what I can see in the code above, you call add_data from your databasecon class, which has an instance p of Person. Since you are not passing a Person object to your add_data method, the empty, unset p object is what is being saved to the database.
Adding a Person parameter to add_data and use that when saving the data to the database.
There are several things I don't like in your code.
Let's start however with your specific problem:
Your code contains also a source of security issues and malignous SQL code injection.
You are saving always an empty person and there is a problem with your SQL connection string.
Try this code instead.
private void addbtn_Click(object sender, EventArgs e)
{
try
{
persons p = new persons(); // we use a new instance of person class
p.p_fname = this.fname.Text;
p.p_lname = this.lname.Text;
p.p_age = this.age.Text;
p.p_gender = this.gender.Text;
p.p_address = this.address.Text;
d.add_data(p); // we save the instance of persons
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error : " + e);
}
}
...
class databasecon
{
public void add_data(person p) // we need a person as parameter
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=../dbsample.mdb";
con.Open();
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
// this is the correct sql command string
cmd.CommandText = "INSERT INTO person(u_fname,u_lname,u_age,u_gender,u_address) " +
VALUES (#u_fname, #u_lname, #u_age, #u_gender, #u_address)";
cmd.Parameters.AddWithValue("u_fname", p.p_fname);
cmd.Parameters.AddWithValue("u_lname", p.p_lname);
cmd.Parameters.AddWithValue("u_age", p.p_age);
cmd.Parameters.AddWithValue("u_gender", p.p_gender);
cmd.Parameters.AddWithValue("u_address", p.p_address);
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
...
}
Now let's talk about code style.
Is a good thing to use CamelCase style in your code, look on the web about C# CamelCase:
Classes and properties should all start with a capitalized letter.
Your class express a single person not a list of persons so its name should be public class Person.
Avoid the use achronims or of short names when you can...
p_lname should be LastName, people will thanks you if you make your code more readable, C# is not C and C# is not PHP!
A field or a property with a longer name will not consume more memory than a property with a short and unreadable name :)
Use always strong typing... age is not a string, age is an integer.
The property should be public int Age, not a string!
Never use MessageBox in your non-visual classes.
Try to catch for exceptions in your client code, not in your library code!
I dont know if I 100% understand the issue about I guess it's because your inserting an empty persons class into the db.
Your `add_data method should take a person object like so.
public void add_data(persons obj)
{
p = obj;
you must pass person object to add_data method
public void add_data(persons p)
{
...
}
and call it:
d.add_data(p);

Categories