C# Bringing the value twice error - c#

public MenClothing(string text)
{
InitializeComponent();
txtUsername.Text = text;
}
Hello so when we tried to carry a value from form1 > form2(label) > form3(textbox) with added this below it gives a error:
Error System.InvalidOperationException: The connectionString Property has not been initialized at System.Data.OleDbConnection.PermissionDemand .
Update:After adding that below, it shows this error enter image description here
public partial class MenClothing : Form
{
OleDbConnection connect = new OleDbConnection();
public MenClothing(string text)
{
InitializeComponent();
txtUsername.Text = text;
}
public MenClothing()
{
InitializeComponent();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C: \Users\Teronkee\Desktop\OFFICAL STAC\OFFICAL STAC\StacProductions\DatabaseSaveItem.accdb";
}
private int upperCase(string pass)
{
int num = 0;
foreach (char ch in pass)
{
if (char.IsUpper(ch))
{
num++;
}
}
return num;
}
private void btnlogout_Click(object sender, EventArgs e)
{
this.Hide();
Form2 Return = new Form2(txtUsername.Text);
Return.ShowDialog();
}
private void MenClothing_Load(object sender, EventArgs e)
{
try
{
connect.Open();
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.ImageLocation = ItemUrl.Text;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
pictureBox1.ImageLocation = ItemUrl.Text;
}
private void button1_Click(object sender, EventArgs e)
{
{
try
{
connect.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "insert into RegisterItem([Name], [Url],[Description], [Price]) values('" + ItemName.Text + "','" + ItemUrl.Text + "','" + ItemDescription.Text + "','" + ItemPrice.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
connect.Close();
}
string str = ItemUrl.Text;
pictureBox1.ImageLocation = str;
//string str = textBox1.Text;
// Image img = Image.FromFile(str);
// pictureBox1.Image = img;
txtUsername = txtID1;
ItemName = txtName1;
ItemDescription = txtDescription1;
ItemPrice = txtPrice1;
ItemName.Text = "";
ItemDescription.Text = "";
ItemPrice.Text = "";
}
}
private void label5_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtUsername.Text == txtID1.Text)
{
}
}
}
}

You are not setting the connection string in the constructor accepting a string.
Change it like so:
public MenClothing(string text)
{
InitializeComponent();
txtUsername.Text = text;
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C: \Users\Teronkee\Desktop\OFFICAL STAC\OFFICAL STAC\StacProductions\DatabaseSaveItem.accdb";
}
or better, to avoid code duplication, move the line setting the connectionstring to its own function and call it from both constructors

Related

Basic looping login menu

I'm trying to make my login system reject a blank space. I've used a while loop to try and make it loop back but it wont work. Ive currently made it only 0-9 is accepted, but would rather any numbers are accepted and just blank spaces are looped back to login again after a message box. Any help would be appreciated, thanks
namespace OrderingSystem
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "1")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button2_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "2")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void lblPin_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "3")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button4_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "4")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button5_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "5")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button6_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "6")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button7_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "7")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button8_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "8")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button9_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "9")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
private void button10_Click(object sender, EventArgs e)
{
Button num = (Button)sender;
if (num.Text == "0")
{
lblPin.Text = lblPin.Text + num.Text;
}
}
public static string server = "";
private void btnEnter_Click(object sender, EventArgs e)
{
bool IncorrectPin = true;
while (IncorrectPin)
{
if (lblPin.Text == "1")
{
server = "Oli";
IncorrectPin = false;
}
else if (lblPin.Text == "0")
{
server = "Training";
IncorrectPin = false;
}
else if (lblPin.Text == "2" + "3" + "4" + "5" + "6" + "7" + "8" + "9")
{
server = "Please Login";
IncorrectPin = false;
}
else
{
MessageBox.Show("Please enter a pin 0-9");
}
}
this.Hide();
TillView sistema = new TillView();
sistema.ShowDialog();
this.Close();
}
private void Login_Load(object sender, EventArgs e)
{
}
}
}
This isn't perfect by any means, but should get the behavior you want. Don't see any need for a loop.
Per your comment
but would rather any numbers are accepted
I do no tests against numberEntered. But you could check that against a range if you wanted.
private void btnEnter_Click(object sender, EventArgs e)
{
int numberEntered = -1;
//Presuming you only want integers
//This returns false if we can't convert the text to an int
if (!int.TryParse(lblPin.Text, out numberEntered))
{
MessageBox.Show("Please enter a pin using numbers only, no spaces");
return;
}
if (numberEntered == 1)
{
server = "Oli";
}
else if (numberEntered == 0)
{
server = "Training";
}
else
{
server = "Please Login";
}
this.Hide();
TillView sistema = new TillView();
sistema.ShowDialog();
this.Close();
}

Search button in DataGridView with textboxchanged

I want to do search button in DataGridView. I read my data with this code:
private void button1_Click_1(object sender, EventArgs e)
{
FileStream f1 = new FileStream("zapis.dat", FileMode.Open);
BinaryReader br = new BinaryReader(f1);
int а = 0;
while (f1.Position < f1.Length)
{
string data = br.ReadString();
string sing = br.ReadString();
string avtor = br.ReadString();
string zagl = br.ReadString();
string janr = br.ReadString();
string ezik = br.ReadString();
dataGridView1.Rows.Add(++а, ezik, zagl, avtor, janr, sing, data);
}
f1.Close();
}
I trying to do button with code:
private void textBox1_TextChanged(object sender, EventArgs e)
if (string.IsNullOrEmpty(textBox1.Text))
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
}
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox1.Text);
}
}
but when I started, I get error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
(... as System.Data.DataTable) returned null.
on:
else
{
(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", textBox1.Text);
How I can fix it?
You are not using DataTable as datasource for DataGridView.
Use a class to represent your data, then you will be able to do the job without "heavy" DataTable.
public class Item
{
public string Data { get; set; }
public string Sing { get; set; }
public string Avtor { get; set; }
// and so on ...
}
// Save data into private class member
private List<Item> _loadedData = new List<Item>();
private void button1_Click_1(object sender, EventArgs e)
{
using (var stream = new FileStream("zapis.dat", FileMode.Open))
using (var reader = new BinaryReader(stream))
{
var data = new List<Item>();
while (stream.Position < stream.length)
{
var item = new Item
{
Data = reader.ReadString(),
Sing = reader.ReadString(),
Avtor = reader.ReadString()
};
data.Add(item)
}
// update private member with newly loaded data
_loadedData = data;
}
// Bind loaded data to the DataGridView
datagridview1.DataSource = _loadedData;
}
Filtering can be done with simple Where method for _loadedData collection.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var filtered = _loadedData.Select(item => item);
if (string.IsNullOrEmpty(textBox1.Text) == false)
{
filtered = filtered.Where(item => item.Avtor == textBox1.Text);
}
datagridview1.DataSource = filtered.ToList();
}

Printing Class information C# Forms

I'm trying to make a program which stores a bunch of country information from a country class in an AVL tree. I am using a form which prints out the list of countries which is saved in a CSV file and when I click on a country I want the program to print out information which corresponds to the selected country.
The problem I am having is getting it to print out the GDP in a text box when I select a country in the list box.
What code can I put to into list box which will print the gdp into a textbox?
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
}
.
namespace country
{
public partial class Form1 : Form
{
AVLTree<Country> myTree = new AVLTree<Country>();
List<Country> Countries = new List<Country>();
static string[] headers = new string[6];
string buffer = "";
public Form1()
{
InitializeComponent();
const int MAX_LINES_FILE = 50000;
string[] AllLines = new string[MAX_LINES_FILE];
AllLines = File.ReadAllLines("countries.CSV");
foreach (string line in AllLines)
{
if (line.StartsWith("Country"))
{
headers = line.Split(',');
}
else
{
string[] columns = line.Split(',');
LinkedList<string> tradePartner = new LinkedList<string>();
string[] partners = columns[5].Split(';', '[', ']');
foreach (string x in partners)
{
if (x != "")
{
tradePartner.AddLast(x);
}
}
myTree.InsertItem(new Country(columns[0], float.Parse(columns[1]), float.Parse(columns[2]), float.Parse(columns[3]), float.Parse(columns[4]), tradePartner));
}
}
myTree.PreOrder(ref buffer);
Console.WriteLine("Tree Contains " + buffer);
Add();
}
private void Add()
{
myTree.CInOrder(ref Countries);
foreach (Country y in Countries)
{
listBox1.Items.Add(y.Countryname);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
country class
public Country (string cn, float gd, float i, float tb, float hd, LinkedList<string> mt)
{
this.Countryname = cn;
this.gdp = gd;
this.inflation = i;
this.tradeBalance = tb;
this.hdi = hd;
this.mtp = mt;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return Countryname.CompareTo(temp.Countryname);
}
public override string ToString()
{
foreach (string i in mtp)
x += i + ",";
return Countryname + " " + gdp + " " + inflation + " " + tradeBalance +" " + hdi + " " + x;
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Country country = (Country)listBox1.SelectedValue;
if (country != null )
textBox1.Text = country.gdp;
}

Selecting and displaying certain items from list based on specific property

i have a list of objects saved in a text file that I can display onto a form. However now I need a button that will only display certain objects from the list based on a property, in my case brand. Below is the code I've been trying to use but cant get it to work.
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
Underneath is the full code, in case more information is needed, thanks for your help.
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.IO;
namespace Car_Manager
{
public partial class Form1 : Form
{
string currentfile;
Car c;
int curIndex = -1;
List<Car> cars = new List<Car>();
public Form1()
{
InitializeComponent();
c = new Car();
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.FileName = "myText";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter =
"Text files (*.txt)|*.txt|All files (*.*)|*.*";
}
public void clearForm()
{
txtBrand.Text = "";
txtModel.Text = "";
txtYear.Text = "";
txtPrice.Text = "";
txtNumMiles.Text = "";
txtInformation.Text = "";
radAutomatic.Checked = false;
radManual.Checked = false;
radConvertible.Checked = false;
radCoupe.Checked = false;
radEstate.Checked = false;
radHatchback.Checked = false;
radHPV.Checked = false;
radSaloon.Checked = false;
radSUV.Checked = false;
}
private void DisplayCar()
{
txtBrand.Text = c.Brand;
txtModel.Text = c.Model;
txtYear.Text = c.Year;
txtPrice.Text = c.Price;
txtNumMiles.Text = c.NumMiles;
DisplayBody();
DisplayGear();
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void FormToObject()
{
c.Brand = txtBrand.Text;
c.Model = txtModel.Text;
c.Year = txtYear.Text;
c.Price = txtPrice.Text;
c.NumMiles = txtNumMiles.Text;
BodyCheck();
GearCheck();
}
private void BodyCheck()
{
if (radHatchback.Checked == true)
{ c.Body = radHatchback.Text; }
else if (radHPV.Checked == true)
{ c.Body = radHPV.Text; }
else if (radSUV.Checked == true)
{ c.Body = radSUV.Text; }
else if (radSaloon.Checked == true)
{ c.Body = radSaloon.Text; }
else if (radConvertible.Checked == true)
{ c.Body = radConvertible.Text; }
else if (radCoupe.Checked == true)
{ c.Body = radCoupe.Text; }
else if (radEstate.Checked == true)
{ c.Body = radEstate.Text; }
}
private void DisplayBody()
{
if (c.Body == "Hatchback")
{ radHatchback.PerformClick(); }
else if (c.Body == "HPV")
{ radHPV.PerformClick(); }
else if (c.Body == "SUV")
{ radSUV.PerformClick(); }
else if (c.Body == "Convertible")
{ radConvertible.PerformClick(); }
else if (c.Body == "Saloon")
{ radSaloon.PerformClick(); }
else if (c.Body == "Coupe")
{ radSaloon.PerformClick(); }
else if (c.Body == "Estate")
{ radEstate.PerformClick(); }
}
private void GearCheck()
{
if (radAutomatic.Checked == true)
{ c.GearBox = radAutomatic.Text; }
else if (radManual.Checked == true)
{ c.GearBox = radManual.Text; }
}
private void DisplayGear()
{
if (c.GearBox == "Manual")
{ radManual.PerformClick(); }
else if (c.GearBox == "Automatic")
{ radAutomatic.PerformClick(); }
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
currentfile = openFileDialog1.FileName;
saveToolStripMenuItem.Enabled = true;
Stream s1 = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(s1);
while (reader.Peek() != -1)
{
string str = reader.ReadLine();
Car c = new Car();
c.ReadString(str);
cars.Add(c);
}
curIndex = 0;
c = cars[curIndex];
DisplayCar();
reader.Close();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save everything in a dialog box
saveFileDialog1.ShowDialog();
// Open the file and save the information
Stream textOut = saveFileDialog1.OpenFile();
StreamWriter writer = new StreamWriter(textOut);
FormToObject();
string str = c.GetToString();
writer.WriteLine(str);
writer.Close();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save the file with the current file name
FileStream f1 = new FileStream(currentfile, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(f1);
// get the object into a string
FormToObject();
StreamWriter file = new System.IO.StreamWriter(f1);
cars.ForEach(file.WriteLine);
file.Close();
}
private void btnAddInfo_Click(object sender, EventArgs e)
{
c.Information.Add(txtAddInfo.Text);
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtInformation.Text = "";
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void btnPreviousCar_Click(object sender, EventArgs e)
{
curIndex--;
if (curIndex < 0)
curIndex = cars.Count - 1;
c = cars[curIndex];
DisplayCar();
}
private void btnNextCar_Click(object sender, EventArgs e)
{
curIndex++;
if (curIndex >= cars.Count)
curIndex = 0;
c = cars[curIndex];
DisplayCar();
}
private void button1_Click(object sender, EventArgs e)
{
int a = cars.Count;
textBox1.Text = Convert.ToString(cars[2]);
}
private void btnEditCar_Click(object sender, EventArgs e)
{
txtBrand.ReadOnly = false;
txtModel.ReadOnly = false;
txtYear.ReadOnly = false;
txtPrice.ReadOnly = false;
txtNumMiles.ReadOnly = false;
txtAddInfo.ReadOnly = false;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
private void yearToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
}
class Car
{
//List of properties
private string brand;
private string model;
private string year;
private string price;
private string numMiles;
private string body;
private string gearbox;
private List<string> information;
//Constructor
public Car() //Default Constructor
{
brand = "Unknown";
model = "Unknown";
year = "Unknown";
price = "Unknown";
numMiles = "Unknown";
information = new List<string>();
}
public Car(string str)
{
information = new List<string>();
ReadString(str);
}
public void ReadString(string str)
{
string[] words = str.Split('|');
int Nwords = words.Count();
brand = words[0];
model = words[1];
year = words[2];
price = words[3];
numMiles = words[4];
body = words[5];
gearbox = words[6];
information.Clear();
for (int i = 7; i < Nwords; i++)
information.Add(words[i]);
}
//Methods
public string Brand
{
get { return brand; }
set { brand = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public string Year
{
get { return year; }
set { year = value; }
}
public string Price
{
get { return price; }
set { price = value; }
}
public string NumMiles
{
get { return numMiles; }
set { numMiles = value; }
}
public string Body
{
get { return body; }
set { body = value; }
}
public string GearBox
{
get { return gearbox; }
set { gearbox = value; }
}
public List<string> Information
{
get { return information; }
set { information = value; }
}
public string GetToString()
{
string str = "";
str += brand + "|";
str += model + "|";
str += year + "|";
str += price + "|";
str += numMiles + "|";
str += body + "|";
str += gearbox + "|";
for (int i = 0; i < information.Count(); i++)
str += information[i] + "|";
return str;
}
}
}
First thing that I noticed:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
// You already have list of cars, this line will copy your list
// into a new one, which is unnecessary work (you don't use it later).
// You don't need this:
List<Car> BrandSelect = new List<Car>(cars);
// the "c" here is not the "c" that is the field of your form
// it's a part of the syntax of linq query
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
// This method displays what is in the field "c" (this.c)
// ... and the content of "c" didn't change at all
DisplayCar();
}
the code here should be, for example:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
//beware this can be null
this.c = (from a in this.cars
where a.Brand == textBox1.Text
select a).FirstOrDefault();
}
[msdn] introduction to linq queries

C# how to load listview

im doing a windows form application to open and load a database. the code needs to show single record view of the records and the listView view however i am stuck on the listVIew part.
here is the following code
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADOX;
namespace Ex3
{
public partial class changeButton : Form
{
public List<Client> ClientRecords = new List<Client>(); //Creates a list for the records to be stored
public string filename;
public string fileDir;
public string rec;
public bool checkBC;
public bool checkLC;
public string dataBaseFile;
public OleDbConnection conn;
public changeButton()
{
InitializeComponent();
}
int position = 0;
private void Form1_Load(object sender, EventArgs e)
{
credBalBox.Maximum = 9999999999;
savingBalBox.Maximum = 9999999999;
}
private void ConnectToDataBase()
{
try
{
string strConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
dataBaseFile + ";";
conn = new OleDbConnection(strConn);
conn.Open();
}
catch (OleDbException e)
{
MessageBox.Show("Failed to connect to database: " + e.Message);
}
}
private void nextButton_Click(object sender, EventArgs e)
{
if (position < ClientRecords.Count - 1)
{
position++;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
private void previousButton_Click(object sender, EventArgs e)
{
if (position > 0)
{
position--;
Print();
}
else
{
MessageBox.Show("Outside of the record limit");
}
}
public void Print()
{
int positionAdd1;
positionAdd1 = position;
positionAdd1++;
currentRecLab.Text = positionAdd1.ToString();
MaxRecLab.Text = ClientRecords.Count.ToString();
if (position >= 0 && position < ClientRecords.Count)
{
nameBox.Text = ClientRecords[position].Name;
suburbBox.Text = ClientRecords[position].Suburb;
postBox.Text = ClientRecords[position].Postcode;
credBalBox.Text = ClientRecords[position].CreditBal.ToString();
savingBalBox.Text = ClientRecords[position].SavingBal.ToString();
}
else
{
nameBox.Text = "";
suburbBox.Text = "";
postBox.Text = "";
credBalBox.Text = "";
savingBalBox.Text = "";
}
}
private void addButton_Click(object sender, EventArgs e)
{
string sameAddName = "null";
string addName;
string addSuburb;
string addPostcode;
decimal addCredBal;
decimal addSavBal;
addName = nameBox.Text;
addSuburb = suburbBox.Text;
addPostcode = postBox.Text;
addCredBal = decimal.Parse(credBalBox.Text);
addSavBal = decimal.Parse(savingBalBox.Text);
string sqlPrefix = "INSERT INTO Client VALUES ";
string data = "(" + "'" + addName + "','" + addSuburb + "','" + addPostcode + "','" + addCredBal + "','" + addSavBal + "'" + ")";
string sql = sqlPrefix + data;
foreach (Client client in ClientRecords)
{
if (addName == client.Name)
{
sameAddName = "Name is not unique. Please use a unique name";
}
}
if (sameAddName == "null" && addSuburb != null)
{
ClientRecords.Add(new Client(addName, addSuburb, addPostcode, addCredBal, addSavBal));
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
int positions = ClientRecords.Count;
currentRecLab.Text = positions.ToString();
MaxRecLab.Text = positions.ToString();
nameBox.Text = addName;
suburbBox.Text = addSuburb;
postBox.Text = addPostcode;
credBalBox.Text = addCredBal.ToString();
savingBalBox.Text = addSavBal.ToString();
position = ClientRecords.Count - 1;
}
else
{
if ((sameAddName != "null") && (addSuburb == "") && (addPostcode == ""))
{
MessageBox.Show(sameAddName + "\nAlso, one of the fields are empty. Please fill it in before adding a new record");
}
else if (sameAddName != "null")
{
MessageBox.Show(sameAddName);
}
}
}
private void removeButton_Click(object sender, EventArgs e)
{
int recPosition = int.Parse(currentRecLab.Text);
recPosition = recPosition - 1;
position = 0;
ClientRecords.Remove(ClientRecords[recPosition]);
Print();
if (MaxRecLab.Text == "0")
{
currentRecLab.Text = "0";
}
}
private void loadButton_Click_1(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand ("SELECT * FROM Client", conn);
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Client nClient = new Client(rdr[0].ToString(), rdr[1].ToString(), rdr[2].ToString(), decimal.Parse(rdr[3].ToString()), decimal.Parse(rdr[4].ToString()));
ClientRecords.Add(nClient);
Print();
}
}
}
private void connectButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Select DataBase";
if (dialog.ShowDialog() == DialogResult.OK)
{
dataBaseFile = dialog.FileName;
DatabaseNameBox.Text = dataBaseFile;
ConnectToDataBase();
}
}
private void DatabaseNameBox_TextChanged(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void nameBox_TextChanged(object sender, EventArgs e)
{
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
public class Client
{
protected string name;
protected string suburb;
protected string postcode;
protected decimal creditBal;
protected decimal savingBal;
public Client(string name, string suburb, string postcode, decimal creditBal, decimal savingBal)
{
this.name = name;
this.suburb = suburb;
this.postcode = postcode;
this.creditBal = creditBal;
this.savingBal = savingBal;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Suburb
{
get
{
return suburb;
}
set
{
suburb = value;
}
}
public string Postcode
{
get
{
return postcode;
}
set
{
postcode = value;
}
}
public decimal CreditBal
{
get
{
return creditBal;
}
set
{
creditBal = value;
}
}
public decimal SavingBal
{
get
{
return savingBal;
}
set
{
savingBal = value;
}
}
}
}
thanks in advance
further info
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
i want to be able to put the code here and when i click the load button from above it should load the listview
To load a listview I would use the following function - it uses a array of string and listviewitem do add items to a listview.
private void LoadListview()
{
string NAME = "John DOE";
string AGE = "30";
string SEX = "MALE";
string DOB = "08/28/1988";
string[] rowa = { NAME, AGE, SEX, DOB };
var listViewItema = new ListViewItem(rowa);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
listView1.Items.Add(listViewItema);
}
You can find a step by step detail answer on my website: http://softvernow.com/2018/05/01/create-list-of-objects-and-load-listview-using-c/

Categories