Hi I am a student do anybody know after populating the combobox with the database values. How to display the same value in the text box. When I select a name in the combobox the same name should be displayed in the text box I am using seleted item. Here is the code.
I am getting the error the following error using the foreach loop
foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DBExample
{
public partial class Form1 : Form
{
private OleDbConnection dbConn; // Connectionn object
private OleDbCommand dbCmd; // Command object
private OleDbDataReader dbReader;// Data Reader object
private Member aMember;
private string sConnection;
// private TextBox tb1;
// private TextBox tb2;
private string sql;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
// Construct an object of the OleDbConnection
// class to store the connection string
// representing the type of data provider
// (database) and the source (actual db)
sConnection =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=c:member.mdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
// Construct an object of the OleDbCommand
// class to hold the SQL query. Tie the
// OleDbCommand object to the OleDbConnection
// object
sql = "Select * From memberTable Order " +
"By LastName , FirstName ";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
// Create a dbReader object
dbReader = dbCmd.ExecuteReader();
while (dbReader.Read())
{
aMember = new Member
(dbReader["FirstName"].ToString(),
dbReader["LastName"].ToString(),
dbReader["StudentId"].ToString(),
dbReader["PhoneNumber"].ToString());
// tb1.Text = dbReader["FirstName"].ToString();
// tb2.Text = dbReader["LastName"].ToString();
// tb1.Text = aMember.X().ToString();
//tb2.Text = aMember.Y(aMember.ID).ToString();
this.comboBox1.Items.Add(aMember.FirstName.ToString());
// this.listBox1.Items.Add(aMember.ToString());
// MessageBox.Show(aMember.ToString());
// Console.WriteLine(aMember.ToString());
}
dbReader.Close();
dbConn.Close();
}
catch (System.Exception exc)
{
MessageBox.Show("show" + exc);
}
}
private void DbGUI_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.textBox1.Text = comboBox1.SelectedItem.ToString();
textBox2.Text = string.Empty;
foreach (var item in comboBox1.SelectedItem)
textBox2.Text += item.ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
You just need to change the foreach loop to:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.textBox1.Text = comboBox1.SelectedItem.ToString();
textBox2.Text = string.Empty;
foreach (var item in comboBox1.Items)
textBox2.Text += item.ToString();
}
the above foreach(var item in comboBox1.Items)
item.ToString() just returns the system type
the below example worked for me to find the one I needed
foreach(DataRowView item in cmbUser.Items)
{
if(item.Row[0].ToString() == "something")\\gets value displayed
{
//do something
}
}
Related
The program is made in C# and database is MySQL.
I have 2 errors, first one when program loads (parameter is not valid) and second one (You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(Slika) values (_binary '?PNG).
So i tried the #blob thing (before i was only saving it as pictureBox which people said its false) and i get this error.
Also good to mention that i always get saved the same file which is BLOB - 55B.
This is the code:
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
I get parameter is invalid in this code where image has to load from database as soon as program is started:
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the whole code of the Form2 (Form1 works perfectly fine):
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 MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
public Form2()
{
InitializeComponent();
}
public byte[] save(PictureBox pb)
{
MemoryStream mstr = new MemoryStream();
pictureBox3.Image.Save(mstr, pb.Image.RawFormat);
return mstr.GetBuffer();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Thanks for any help!!
UPDATE
So I have decided to insert full data and image directly to table in phpmyadmin and when I entered credentials no errors were showing.
It just seems to be an error while converting to blob while updating the table, now if someone can help me with this i'm pretty new to C# and MySQL especially.
[1]: https://i.stack.imgur.com/KUK7a.png
UPDATE #2
I have changed mstr.GetBuffer() to mstr.GetArray(), also I added few lines to code and there are no more errors at saving picture, but I still have problem when it gets saved its corrupted or it just doesn't convert correctly.
When image gets uploaded it doesn't take nearly as much memory as same image i inserted directly into the table which had no problem loading into program.
So now it's just problem converting to binary ! guess, any help is appreciated!
This is how code looks after I added couple lines to save button:
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika = '" + ImageData + "' where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Slika", ImageData);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Refresh();
con.CloseConnection2();
}
I am happy to say that the problem has been fixed, it was indeed problem with saving picture to the database.
The problem was that I had to add parameter MySqlDbType.Blob like so:
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
And then I had to give that parameter the picture, like so:
cmd.Parameters["#Slika"].Value = ImageData;
Easy as that, feels much more rewarding when you solve the problem yourself :D
I will post the whole code so if someone wants to use it feel free.
Code:
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 MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
string fname;
public Form2()
{
InitializeComponent();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try {
string query = "select Slika,ID from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch
{
MessageBox.Show("Error: Profilna slika nije pronadjena!");
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
fname = dialog.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika= #Slika where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
cmd.Parameters["#Slika"].Value = ImageData;
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.CloseConnection2();
pictureBox2.Image = pictureBox3.Image;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox3.Image = pictureBox2.Image;
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Enjoy!
PS. Slika or #Slika means image in my language, its just that I called my image column in the database like that.
This is my first time attempting to read an Access database and write each row to the console. When I execute the application I get thrown an exception that says, "No value given for one or more required parameters" on the following statement:
OleDbDataReader reader = cmd.ExecuteReader();
I'm relatively new to c# programming and after hours of research, I can't figure out what I'm doing wrong. Here's my code:
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
In response to the commenters, I'm posting a larger piece of code to eliminate any assumptions and give a better overall picture of what I'm trying to do:
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.OleDb;
using System.IO;
namespace AzFloodSquad
{
public partial class frm1DefaultScreen : Form
{
//Initialize the application
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Databases\\AzFloodSquad\\AzFloodSquad.accdb;Persist Security Info=False;";
OleDbConnection conn = null;
String error_message = "";
String q = "";
string varReportId = "";
public frm1DefaultScreen()
{
InitializeComponent();
}
//Load the default form
private void frm1DefaultScreen_Load(object sender, EventArgs e)
{
connectToolStripMenuItem.PerformClick();
contactsToolStripMenuItem.PerformClick();
}
//Exit the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
//Start the database
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn = new OleDbConnection(conn_string);
conn.Open();
disconnectToolStripMenuItem.Enabled = true;
connectToolStripMenuItem.Enabled = false;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Stop the database
private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
conn.Close();
disconnectToolStripMenuItem.Enabled = false;
connectToolStripMenuItem.Enabled = true;
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
//Clean up database whem form close button clicked
private void frm1DefaultScreen_FormClosing(object sender, FormClosingEventArgs e)
{
disconnectToolStripMenuItem.PerformClick();
}
private void contactsToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "Contacts";
q = "SELECT * " +
"FROM CONTACTS WHERE CONTACTS.CONTACT_TYPE = 'CUSTOMER' " +
"OR CONTACTS.CONTACT_TYPE = 'HOMEOWNER' OR CONTACTS.CONTACT_TYPE = 'HOME OWNER' " +
"OR CONTACTS.CONTACT_TYPE = 'TENANT'" +
"ORDER BY FULL_NAME";
this.Cursor = Cursors.WaitCursor;
run_Query_Parm(q);
this.Cursor = Cursors.Default;
}
//Pull data from the database using the parameter field
private void run_Query_Parm(String q)
{
error_message = "";
try
{
OleDbCommand cmd = new OleDbCommand(q, conn);
OleDbDataAdapter a = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
a.SelectCommand = cmd;
a.Fill(dt);
results.DataSource = dt;
results.AutoResizeColumns();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
//Clear all data from the screen
private void clearFormToolStripMenuItem_Click(object sender, EventArgs e)
{
varReportId = "";
if (this.results.DataSource != null)
{
this.results.DataSource = null;
}
else
{
this.results.Rows.Clear();
}
}
private void maintenanceToolStripMenuItem_Click(object sender, EventArgs e)
{
//Use a variable to hold the SQL statement.
string inputString = "SELECT Full_Name, First_Name, Last_Name, Company FROM CONTACTS";
try
{
//Create an OleDbCommand object and pass in the SQL statement and OleDbConnection object
OleDbCommand cmd = new OleDbCommand(inputString, conn);
//Send the CommandText to the connection, and then build an OleDbDataReader.
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetString(1));
reader.NextResult();
}
}
reader.Close();
}
catch (Exception ex)
{
error_message = ex.Message;
MessageBox.Show(error_message);
}
}
Any help provided would be greatly appreciated. Thanks in advance.
I found the problem. Apparently, I had improper syntax on my SELECT statement. When I replaced my SELECT, (shown in the first code example I posted), with the following, it worked fine:
string inputString = "SELECT Contacts.[Account_Number], " +
"Contacts.[Full_Name], Contacts.[ID], Contacts.[Street], " +
"Contacts.[City], Contacts.[State], Contacts.[Zip] FROM Contacts";
I am new to C# and I am making a simple database project in which I want to add a functionality in which if user enter the identity number and click the button all the records will be displayed in the list boxes... Please help me to complete it... the code I want to add is in the last section of the code in button2_click.
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 main_form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=windowDb;Integrated Security=True;Pooling=False");
SqlCommand command = new SqlCommand();
//SqlDataReader dataSearch;
private void Form1_Load(object sender, EventArgs e) {}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e) {}
private void btn_save_Click(object sender, EventArgs e)
{
if(id_Txt.Text!=""& f_txt.Text!=""& Lname_txt.Text!=""& m_txt.Text!=""& dateTimePicker1.Text!=""){
command.Connection = con;
con.Open();
command.CommandText = "insert into people(id,fname,lname,mobile,TDATE) values('"+id_Txt.Text+"','"+f_txt.Text+"','"+Lname_txt.Text+"','"+m_txt.Text+"','"+dateTimePicker1.Text/*Value.ToString()*/+"')";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void search() {
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
listBox5.Items.Clear();
con.Open();
command.CommandText = "select * from people";
command.Connection = con;
SqlDataReader dataSearch = command.ExecuteReader();
if(dataSearch.HasRows){
while (dataSearch.Read())
{
listBox1.Items.Add(dataSearch["id"].ToString());
listBox2.Items.Add(dataSearch["fname"].ToString());
listBox3.Items.Add(dataSearch["lname"].ToString());
listBox4.Items.Add(dataSearch["mobile"].ToString());
listBox5.Items.Add(dataSearch["TDATE"].ToString());
}
}
con.Close();
}
private void btn_view_Click(object sender, EventArgs e)
{
search();
}
private void bn_update_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "" & f_txt.Text != "" & Lname_txt.Text != "" & m_txt.Text != "" & dateTimePicker1.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "update people set fname='" + f_txt.Text + "',lname='" + Lname_txt.Text + "',mobile='" + m_txt.Text + "',TDATE='" + dateTimePicker1.Text + "' where id='" +id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data updated Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox list = sender as ListBox;
if(list.SelectedIndex!=-1)
{
listBox1.SelectedIndex = list.SelectedIndex;
listBox2.SelectedIndex = list.SelectedIndex;
listBox3.SelectedIndex = list.SelectedIndex;
listBox4.SelectedIndex = list.SelectedIndex;
listBox5.SelectedIndex = list.SelectedIndex;
// retrive to TextBox of AllowDrop events;
/* id_Txt.Text = listBox1.SelectedIndex.ToString();
f_txt.Text = listBox2.SelectedIndex.ToString();
Lname_txt.Text = listBox3.SelectedIndex.ToString();
m_txt.Text = listBox4.SelectedIndex.ToString();
dateTimePicker1.Value = DateTime.Now;*/
id_Txt.Text = listBox1.SelectedItem.ToString();
f_txt.Text = listBox2.SelectedItem.ToString();
Lname_txt.Text = listBox3.SelectedItem.ToString();
m_txt.Text = listBox4.SelectedItem.ToString();
dateTimePicker1.Value = DateTime.Now;
}
}
private void btn_delete_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "delete from people where id='" + id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data deleted Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void label1_Click(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {}
private void button2_Click(object sender, EventArgs e)
{
if (text_search.Text == "")
{
MessageBox.Show("Enter the Rollno.");
}
else {
}
}
}
}
I have been following the documentation here:
http://msdn.microsoft.com/en-us/library/0f92s97z%28v=vs.100%29.aspx
However, I cannot get my application to work!
please see my short video: https://www.youtube.com/watch?v=zpOCaT6NaGs
My Application is not working, I am having nightmares trying to get it working.
I want to make a 'Stock management System',
Requirements:
Browse through products (Name, Price)
Add Products to the Table
Edit Existing Products
Remove Existing Products
Save changes to the Table
Create an Order form that will allow for listing selected products and providing a quantity selected and cost displayed
Print the results.
I cannot seem to get the data to save to the database table without problems.
My System:
Windows 7 - SP1
Visual Studio 2010 Professional
Using a Microsoft Access Database (DataSet)
1 Table to connect
3 fields: "ID, proName, proPrice"
Any Help is very welcome, Thanks.
My Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace KanadaStockControl
{
public partial class frmProducts : Form
{
stockDataSet dsoc;
OleDbConnection conn;
OleDbDataAdapter da;
public frmProducts()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
////Adding the items to the database
//dboKanadaDataSetProducts.ProductsRow newProductsRow;
//newProductsRow = dboKanadaDataSetProducts.Products.NewProductsRow();
////Setting the Product Name
//newProductsRow.ProductName = txtItem.Text;
////Setting the Product Price
//newProductsRow.ListPrice = txtPrice.Text;
////Adding the new row to the table
//this.dboKanadaDataSetProducts.Products.Rows.Add(newProductsRow);
////Saving the new row to the database
//this.productsTableAdapter.Update(this.dboKanadaDataSetProducts.Products);
//Old NON WORKING DATABASE ADD CODE:
//dboKanadaDataSetProductsTableAdapters.ProductsTableAdapter productsTableAdapter = new dboKanadaDataSetProductsTableAdapters.ProductsTableAdapter();
//productsTableAdapter.Insert("9", "NA", "0", txtPrice.Text, "Software");
//lstPrice.Items.Add(txtPrice.Text);
//lstItem.Items.Add(txtItem.Text);
stockDataSetTableAdapters.stockTableAdapter stockTableAdaptor = new stockDataSetTableAdapters.stockTableAdapter();
stockTableAdapter.Insert(txtItem.Text, txtPrice.Text);
}
//private void lstItem_SelectedIndexChanged(object sender, EventArgs e)
//{
// int x = lstItem.SelectedIndex;
// lstPrice.SelectedIndices.Add(x);
//}
//private void lstPrice_SelectedIndexChanged(object sender, EventArgs e)
//{
// int x = lstPrice.SelectedIndex;
// lstItem.SelectedIndices.Add(x);
//}
private void btnRemove_Click(object sender, EventArgs e)
{
if(1==1/*lstItem.SelectedItem == null*/)
{
MessageBox.Show("You must select an Item first, Before you are able to delete it!");
}
else
{
//Finding the row to delete in the database
//dboKanadaDataSetProducts.ProductsRow delProductsRow;
//delProductsRow = dboKanadaDataSetProducts.Products.FindByProductsID(string ProductName);
//START -------
// Locate the row to delete.
//NorthwindDataSet.RegionRow oldRegionRow;
//oldRegionRow = northwindDataSet.Region.FindByRegionID(5);
// Delete the row from the dataset
//oldRegionRow.Delete();
// Delete the row from the database
//this.regionTableAdapter.Update(this.northwindDataSet.Region);
//END -------
//lstPrice.Items.Remove(lstPrice.SelectedItem);
//lstItem.Items.Remove(lstItem.SelectedItem);
}
}
//I cannot be bothered to add spaces to this code, hence the misaligned code.
private void btnClear_Click(object sender, EventArgs e)
{
//lstItem.Items.Clear();
//lstPrice.Items.Clear();
}
private void txtPrice_TextChanged(object sender, EventArgs e)
{
//string context = this.txtPrice.Text;
//for (int i = 0; i < context.Length; i++)
//{
// if (!char.IsNumber(context[i]))
// {
// MessageBox.Show("Only numbers are allowed in this field!");
// txtPrice.Text = txtPrice.Text.Remove(txtPrice.TextLength - 1);
// }
//}
}
private void button2_Click(object sender, EventArgs e)
{
/*
if (MessageBox.Show("Are you sure that you want to DELETE ALL LISTED ITEMS?", "WARNING: Delete All Records",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
== DialogResult.Yes)
{
int j = lstPrice.Items.Count;
for (int i = lstItem.Items.Count; i > 0; )
{
lstItem.Items.Remove(lstItem.Items[--i]);
lstPrice.Items.Remove(lstPrice.Items[--j]);
}
}*/
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
frmOrder makeOrder = new frmOrder();
makeOrder.Show();
}
//private void frmProducts_Load(object sender, EventArgs e)
//{
// // TODO: This line of code loads data into the 'dboKanadaDataSetProducts.Products' table. You can move, or remove it, as needed.
// //this.productsTableAdapter.Fill(this.dboKanadaDataSetProducts.Products);
//}
private void frmProducts_Load_1(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'stockDataSet.stock' table. You can move, or remove it, as needed.
//this.stockTableAdapter.Fill(this.stockDataSet.stock);
dsoc = new stockDataSet();
conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\stock.accdb");
da = new OleDbDataAdapter("Select * from stock", conn);
OleDbCommandBuilder cmdBl = new OleDbCommandBuilder(da);
da.Fill(dsoc, "stock");
dataGridView2.DataSource = dsoc;
dataGridView2.DataMember = "stock";
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//this.Validate();
//this.stockBindingSource.EndEdit();
//this.stockTableAdapter.Update(this.stockDataSet.stock);
//MessageBox.Show("Update successful");
//da.Update(stockDataSet.Tables["stock"]);
System.Data.OleDb.OleDbConnection oledb1 = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\stock.accdb");
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT stock (proName, proPrice) VALUES ("+ txtItem.Text +", " + txtPrice.Text + ")";
cmd.Connection = oledb1;
oledb1.Open();
cmd.ExecuteNonQuery();
oledb1.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}
//this.dataGridView1.EndEdit();
}
private void btnMenu_Click(object sender, EventArgs e)
{
this.Hide();
frmMenu showMenu = new frmMenu();
showMenu.Show();
}
}
}
cmd.CommandText = "INSERT INTO stock (proName, proPrice) VALUES ("+ txtItem.Text +", " + txtPrice.Text + ")";
It will work. But the data will be saved as a copy of database in the bin/debug folder.
Go to Solution explorer and change the properties of Database. Set "Copy to output Directory=Copy if newer" and then try. Good luck.
I have a simple form which connects to a access database and displays records, this code shows whats going on, why is the button im trying to code not working? Im guessing its something to do with the variable which i've not decleared correctly?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace MediaPlayer
{
public partial class Media : Form
{
// Use this connection string if your database has the extension .accdb
private const String access7ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\MediaDatabase.accdb";
// Use this connection string if your database has the extension .mdb
private const String access2003ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\MediaDatabase.mdb";
// Data components
private OleDbConnection myConnection;
private DataTable myDataTable;
private OleDbDataAdapter myAdapter;
private OleDbCommandBuilder myCommandBuilder;
// Index of the current record
private int currentRecord = 0;
private void FillDataTable(String selectCommand)
{
try
{
myConnection.Open();
myAdapter.SelectCommand.CommandText = selectCommand;
// Fill the datatable with the rows reurned by the select command
myAdapter.Fill(myDataTable);
myConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error in FillDataTable : \r\n" + ex.Message);
}
}
private void DisplayRow(int rowIndex)
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[rowIndex];
textBox1.Text = row["FilePath"].ToString();
textBox2.Text = row["Subject"].ToString();
textBox3.Text = row["Title"].ToString();
textBox4.Text = row["Keywords"].ToString();
textBox5.Text = row["MediaType"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
public Media()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
{
String command = "SELECT * FROM Media";
try
{
myConnection = new OleDbConnection(access7ConnectionString);
myAdapter = new OleDbDataAdapter(access7ConnectionString, myConnection);
myCommandBuilder = new OleDbCommandBuilder(myAdapter);
myDataTable = new DataTable();
FillDataTable(command);
DisplayRow(currentRecord);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
int m_rowPosition = 0;
private void label2_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
//if not at the first row, go back one row and show the record.
if (m_rowPosition !=0)
{
m_rowPosition---;
this.DisplayRow();
}
}
private void button6_Click(object sender, EventArgs e)
{
//move to first row of data and show data
m_rowPosition = 0;
this.DisplayRow();
}
}
}
If i understood you want to do this when calling DisplayRow method:
DisplayRow(m_rowPosition);
or you can change your method to this:
private void DisplayRow()
{
// Check that we can retrieve the given row
if (myDataTable.Rows.Count == 0)
return; // nothing to display
if (rowIndex >= myDataTable.Rows.Count)
return; // the index is out of range
// If we get this far then we can retrieve the data
try
{
DataRow row = myDataTable.Rows[m_rowPosition];//<- here you using index which value is changed on button click
textBox1.Text = row["FilePath"].ToString();
textBox2.Text = row["Subject"].ToString();
textBox3.Text = row["Title"].ToString();
textBox4.Text = row["Keywords"].ToString();
textBox5.Text = row["MediaType"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Error in DisplayRow : \r\n" + ex.Message);
}
}
This is being discussed in
why aren't my buttons working in c# application