Saving Data to a Database (Single Table) C# - c#

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.

Related

When I try to load image from mysql database i get error "Parameter is not valid" and when i try to load an image from db

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.

getting an error when try to retrieve datagridview column value "15 digits"

I am trying to code an accounting system into which I should enter a product id, product name and product price. After that it should be stored in a .accdb file
My problem is when I enter more than 10 digits into product id the datagridview gives me an error saying that the value is too large for int32 type.
Error:
Additional information: Value was either too large or too small for an
Int32.Couldn't store <6221060003181> in Item_Code Column. Expected
type is Int32.
When I open the accdb file, I found the data stored; but next time I open the form, it gives me that error!
public partial class Productentry : MetroFramework.Forms.MetroForm
{
public OleDbConnection connection = new OleDbConnection();
public Productentry()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Sama_Software\WindowsFormsApplication1\WindowsFormsApplication1\DB.accdb;Jet OLEDB:Database Password=**************";
}
private void Productentry_Load(object sender, EventArgs e)
{
ViewData();
// TODO: This line of code loads data into the 'dBDataSet.Product' table. You can move, or remove it, as needed.
this.productTableAdapter1.Fill(this.dBDataSet.Product);
ViewData();
}
void ViewData()
{
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Product]",connection);
da.Fill(this.dBDataSet.Product);
}
private void bunifuButton4_Click(object sender, EventArgs e)
{
this.Close();
}
private void bunifuButton3_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("INSERT INTO [Product] (Item_Code, Item_Name, Price) VALUES ('" + Pidn.Text + "','" + name.Text + "','" + price.Text + "')", connection);
da.Fill(dBDataSet)
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void Cat_TextChange(object sender, EventArgs e)
{
}
private void bunifuButton1_Click(object sender, EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("UPDATE [Product] WHERE [Item_Code]=" + Pidn.Text + " SET [Item_Name]='" + name.Text + "',[Price]=" + price.Text + "", connection);
da.Fill(dBDataSet);
ViewData();
Pidn.Clear();
name.Clear();
price.Clear();
}
private void bunifuButton4_Click_1(object sender, EventArgs e)
{
this.Close();
}
private void Pid_TextChange(object sender, EventArgs e)
{
}
}
}
Store the barcode as text.
Even though it is build by digits, it is not a number but a code of fixed length, and it may even have a leading zero.

Automatic insertion of ID in execution

I have created inserting Employee details in Visual studio 2010.When I click on Add,it displays as added and the id automatically increments in backend.But instead of added,if I had to display as ("You EMP ID is somenumber(eg.10) )in front end while execution,what should I do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HRMSController;
using HRMSBusinessEntities;
using System.Data;
namespace HumanResourceManagementSystems
{
public partial class HRMSEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = (string)(Session["LoginUser"]);
if (Session["LoginUser"] != null)
{
lblDisplay.Text = "Welcome..." + username;
}
Calendar1.Visible = false;
Label1.Visible = false;
txtcurrdate.Text = System.DateTime.Now.ToLongDateString();
}
protected void Btnmodified_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Added" ;
Clear();
}
public void Clear()
{
txtname.Text = "";
txtcurrdate.Text = "";
txtmodifieddate.Text = "";
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
txtmodifieddate.Text = Calendar1.SelectedDate.ToString();
}
protected void Button3_Click(object sender, EventArgs e)
{
Clear();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.Visible = true;
}
}
}
After adding the record you can pull up the max id record and show the record in the UI
Query might look like
Select * from Employee ORDER BY EmpId DESC LIMIT 1;
As suggested for performance issue we can do
Select max(EmpId) from Employee;
EDIT
add.Add(record);
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
Label1.Visible = true;
Label1.Text = Your Empl ID is " + LastID[0].ToString() ;
Clear();
con.Close();
Another way could be
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Your Empl ID is " + FetchLastID();
Clear();
}
public string FetchLastID()
{
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
return LastID[0].ToString() ;
}

BindingNavigator with multiple tables updating problem in Visual Studio 2010

I have 2 tables 'contract' and 'customer', they have fk relationship. I drag 'contact' onto form then do so with 'customer', both are details type. The data of 2 tables are shown on form accordingly. The problem is when I modify then click save button only data of 'contract' table is updated.
private void button67_Click(object sender, EventArgs e)
{
if (textBox81.Text == "")
{
MessageBox.Show("you must choose table name");
}
if (textBox81.Text != "")
{
connect();
cmd = new OleDbCommand("select * from " + textBox81.Text + " ", conn);
ds = new DataSet();
dp = new OleDbDataAdapter(cmd);
dp.Fill(ds,""+textBox81.Text+"");
cm = (CurrencyManager)this.BindingContext[ds];
textBox79.DataBindings.Add("text",ds,""+textBox81.Text+""+".ProdS_name");
textBox80.DataBindings.Add("text", ds, "" + textBox81.Text + "" + ".rate");
}
}
private void button58_Click(object sender, EventArgs e)
{
cm.Position++;
}
private void button59_Click(object sender, EventArgs e)
{
cm.Position= cm.Count - 1; ;
}
private void button61_Click(object sender, EventArgs e)
{
cm.Position=0;
}

combobox with for each loop

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
}
}

Categories

Resources