c# how to set beginInvoke end? - c#

I have code my system to save a temporary image file to a folder from the pictureBox then I have to make sure that the beginInvoke end and code the system to delete the temporary image file of that folder. Anyone know how to do that?
This is my code:
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
Bitmap bm = new Bitmap(area);
bm.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
singleFileInfo = new FileInfo(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
var operationStartTime = DateTime.Now;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
operationStartTime = DateTime.Now;
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getImage = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
String getImage1 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[1].Destination.ToString() + "'";
String getImage2 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[2].Destination.ToString() + "'";
SqlCommand cmd = new SqlCommand(getImage, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
getPath = rd["ImagePath"].ToString();
pictureBox4.Image = Image.FromFile(getPath);
}
rd.Close();
SqlCommand cmd1 = new SqlCommand(getImage1, con);
SqlDataReader rd1 = cmd1.ExecuteReader();
while (rd1.Read())
{
getPath1 = rd1["ImagePath"].ToString();
pictureBox5.Image = Image.FromFile(getPath1);
}
rd1.Close();
SqlCommand cmd2 = new SqlCommand(getImage2, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
getPath2 = rd2["ImagePath"].ToString();
pictureBox6.Image = Image.FromFile(getPath2);
}
con.Close();
}
private void pictureBox4_Click(object sender, EventArgs e)
{
if (pictureBox4.Image == null)
{
MessageBox.Show("Nothing has been scanned yet!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getText = "SELECT ImagePath, Character FROM CharacterImage WHERE ImagePath='" + getPath + "'";
SqlCommand cmd = new SqlCommand(getText, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
for (int i = 0; i < 1; i++)
{
String imageChar = rd["Character"].ToString();
Action showText = () => ocrTB.AppendText(imageChar);
ocrTB.Invoke(showText);
}
}
rd.Close();
}
}

BeginInvoke returns you with an IAsyncResult which you can use to wait for the operation to complete:
IAsyncResult result = processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);
You can then check whether the operation completed using the result.IsCompleted property, or you can wait on the WaitHandle returned from result.AsyncWaitHandle.

Related

Save and Retrieve an Image c# WPF Sql

I'm new here and I've also searched about my problem, but I could manage to solve it.
I would like to save and retrieve images to/from Database(SQL) in C# WPF.
I have to make a project about storing a recipe. A recipe contains a table in the Database with the columns: Id, Name, Image, Content.The Information has to be saved and then the name of the recipe(currently done) and images(here is the problem) has to be displayed in a Grid, (so far i don't need to work with the "content" column from the database. That comes later).
I think that I have succeeded in the saving of image to the database, but I am not completely sure. If the saving of the image to the DB is correct, I need a function to retrieve it.
I would be happy for some help. Many Thanks!
D.Tsvet
Thats a sample of the future end result. The image has to be under the name
// Add recipe Window
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public partial class add_Recipe : Window
{
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public add_Recipe()
{
InitializeComponent();
}
// Upload a picture from your device
private void browseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
FileName = op.FileName.ToString();
image_box.Source = new BitmapImage(new Uri(op.FileName));
}
string dbConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\guiProjekte\Stands\Projekt_GUI_200418\Projekt_GUI_20042018\Projekt_GUI_160418\Projekt_GUI\1234\1234\Database.mdf;Integrated Security=True;";
private void saveRecipe_Button(object sender, RoutedEventArgs e)
{
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string q = "insert into recipes(Name,Image,Content)values('" + textBox_newRecipe.Text.ToString() + "','" + ImageData + "','" + content_box.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Connection made Successfuly..!");
this.Close();
myRecipes_Window obj_myRecipes_Window = new myRecipes_Window();
obj_myRecipes_Window.Show();
//Retrieve Recipe Window:
public void FillRecipes()
{
int column = 0;
int row = 0;
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
String sqlSelectQuery = "SELECT * FROM recipes";
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(column < 3)
{
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
else
{
column = 0;
row++;
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
}
}
I made some changes about my post. I'm sorry for the previous unclearness.

Retrieve fingerprints from sql server data VarBinary(Max) in winForm pictureBox

i am using secugen fingerprint reader and sdk ...with sdk i am able to scan fingerprint,match,verify and display fingerprint image in pictureBox on runtime.. but not able to save in database.. i trien my on code to save fingerprints in database..
this is insertion code
private void BtnVerify_Click(object sender, EventArgs e)
{
Int32 iError;
bool matched1 = false;
bool matched2 = false;
SGFPMSecurityLevel secu_level;
secu_level = (SGFPMSecurityLevel)comboBoxSecuLevel_V.SelectedIndex;
iError = m_FPM.MatchTemplate(m_RegMin1, m_VrfMin, secu_level, ref matched1);
iError = m_FPM.MatchTemplate(m_RegMin2, m_VrfMin, secu_level, ref matched2);
if (iError == (Int32)SGFPMError.ERROR_NONE)
{
if (matched1 & matched2)
{
StatusBar.Text = "Verification Success";
//string name = "sumi";
SqlConnection con = new SqlConnection("Data Source=HP; user=sa; password=Admin1; Initial Catalog=schoolmanagement; Integrated Security=True");
string qry = "INSERT into teacher_fingerprint (teacher_id,name,teacher_fingerprints)values (#teacher_id,#name,#teacher_fingerprints)";
SqlCommand cmd = new SqlCommand(qry, con);
MemoryStream stream = new MemoryStream();
pictureBoxV1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
con.Open();
cmd.Parameters.AddWithValue("#teacher_id", comboBox2.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text + " " + textBox3.Text);
//cmd.Parameters.AddWithValue("#teacher_fingerprints", m_VrfMin);
cmd.Parameters.AddWithValue("#teacher_fingerprints",pic);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
StatusBar.Text = "Verification Failed";
}
}
else
DisplayError("MatchTemplate()", iError);
}
and this my DrawImage function
private void DrawImageImg(Byte[] imgData, PictureBox picBox)
{
int colorval;
Bitmap bmp = new Bitmap(m_ImageWidth, m_ImageHeight);
picBox.Image = (Image)bmp;
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
colorval = (int)imgData[(j * m_ImageWidth) + i];
bmp.SetPixel(i, j, Color.FromArgb(colorval, colorval, colorval));
}
}
picBox.Refresh();
}
this my database .. i dont know this fingerprint binary is valid or not?
enter image description here
i tried to select fingerprint data in pictureBox but its not working
it gives out of index error in drawImage function
this is my selection code
m_RegMin5 = new Byte[400];
if (iError == (Int32)SGFPMError.ERROR_NONE)
{
DrawImage(fp_image, pictureBox1);
StatusBar.Text = "Device Message: Finger On";
SqlConnection conn = new SqlConnection(#"Data Source=HP; user=sa; password=Admin1; Initial Catalog=schoolmanagement; Integrated Security=True");
string query = "select teacher_fingerprints from teacher_fingerprint where teacher_id=2 ";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
m_RegMin5 = cmd.ExecuteScalar() as byte[];
DrawImageImg(m_RegMin5,pictureBox2);
}
else
{
DisplayError("GetImage()", iError);
}

Filtering imagelist and listview based on query

It successfully loads items and images from table, but when i try to search nothing comes up
Here's my code on the form load event(works)
public void IL()
{
imageList1.Images.Clear();
listView1.Items.Clear();
listBox1.Items.Clear();
SqlDataReader dr;
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from EnteryItem ", cn);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
try
{
var imageBytes = (byte[])dr["ItemImage"];
MemoryStream memStm = new MemoryStream(imageBytes);
memStm.Seek(0, SeekOrigin.Begin);
Image image = Image.FromStream(memStm);
imageList1.Images.Add(image);
if (dr["ItemName"].ToString() == "")
{
listBox1.Items.Add(dr["ItemBarcode"].ToString());
}
else
{
listBox1.Items.Add(dr["ItemName"].ToString());
}
}
catch
{
Bitmap bmp = new Bitmap(78, 78);
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.Clear(Color.FromKnownColor(KnownColor.ControlDarkDark));
}
imageList1.Images.Add(bmp);
if (dr["ItemName"].ToString() == "")
{
listBox1.Items.Add(dr["ItemBarcode"].ToString());
}
else
{
listBox1.Items.Add(dr["ItemName"].ToString());
}
}
}
dr.Close();
this.imageList1.ImageSize = new Size(100, 100);
imageList1.ColorDepth = ColorDepth.Depth32Bit;
this.listView1.LargeImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
item.Text = listBox1.Items[j].ToString();
this.listView1.Items.Add(item);
}
}
cn.Close();
}
Here is the search code on text change event(here's the problem)
private void search()
{
if (textBox2.Text == "")
{
IL();
}
imageList1.Images.Clear();
listView1.Items.Clear();
listBox1.Items.Clear();
SqlDataReader dr;
cn.Open();
SqlCommand cmd = new SqlCommand("Select * from EnteryItem WHERE ItemName = N'%" + textBox2.Text + "%' Or ItemBarcode = N'" + textBox2.Text + "' ", cn);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
try
{
var imageBytes = (byte[])dr["ItemImage"];
MemoryStream memStm = new MemoryStream(imageBytes);
memStm.Seek(0, SeekOrigin.Begin);
Image image = Image.FromStream(memStm);
imageList1.Images.Add(image);
if (dr["ItemName"].ToString() == "")
{
listBox1.Items.Add(dr["ItemBarcode"].ToString());
}
else
{
listBox1.Items.Add(dr["ItemName"].ToString());
}
}
catch
{
Bitmap bmp = new Bitmap(78, 78);
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.Clear(Color.FromKnownColor(KnownColor.ControlDarkDark));
}
imageList1.Images.Add(bmp);
if (dr["ItemName"].ToString() == "")
{
listBox1.Items.Add(dr["ItemBarcode"].ToString());
}
else
{
listBox1.Items.Add(dr["ItemName"].ToString());
}
}
}
dr.Close();
this.imageList1.ImageSize = new Size(100, 100);
imageList1.ColorDepth = ColorDepth.Depth32Bit;
this.listView1.LargeImageList = this.imageList1;
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
item.Text = listBox1.Items[j].ToString();
this.listView1.Items.Add(item);
}
}
cn.Close();
}
As far as i know sql and wildcards like % works only with a LIKE operator.
SQL Wildcards
First of all: instead of getting new images set every time you type something in your textbox, keep them in a collection maybe and add to your listbox only filtered part of it, like: listBox1.DataSource = SomeLocalCollection.Where(i=>i.ItemName.Contains(textBox2.Text)).ToList()
Also, use debugger to check which part goes wrong in your code.

Keep stuck at the reading the data from database

I would like to minus the data from the database with the value that I give when I run the program. Everything works, but I keep stuck at the newVal. I already did it like this, but the newVal keep appear 0 (because I declared decimal newVal = 0, but on this question, I just used decimal newVal;). Two more problems: if I move the newVal = ... to the top, it is useless, because one of the calculations in the newVal is reading data from the database (since I want database minus with the new value given when i run the program, required dReader = cmd.ExecuteReader();), but if I put the newVal at the bottom after reading data, it is useless as well, because I set the Quantity = ? and the value of ? is newVal.. Well, here is the code:
private void AddObjects(object sender, EventArgs e, Form theForm)
{
button1.Visible = true;
textBoxQuantityContainer = new List<NumericUpDown>();
textBoxCodeContainer = new List<NumericTextBox>();
textBoxDescContainer = new List<TextBox>();
textBoxSubTotalContainer = new List<TextBox>();
textBoxTotalContainer = new List<TextBox>();
textBoxAllTotalContainer = new TextBox();
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT [Code] FROM [Seranne]", conn);
dReader = cmd.ExecuteReader();
AutoCompleteStringCollection codesCollection = new AutoCompleteStringCollection();
while (dReader.Read())
{
string numString = dReader[0].ToString().PadLeft(4, '0');
codesCollection.Add(numString);
}
dReader.Close();
conn.Close();
if (firstForm.comboBox1.SelectedIndex == 0)
{
label1.Text = "Code:";
label1.Location = new Point(60, 125);
label2.Text = "Welcome to the Selling System.";
label2.Location = new Point(600, 30);
label3.Text = "Quantity:";
label3.Location = new Point(155, 125);
label4.Text = "Description:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total on Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total on Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total on Rp:";
label7.Location = new Point(1080, 580);
}
else if (firstForm.comboBox1.SelectedIndex == 1)
{
label1.Text = "Kode:";
label1.Location = new Point(60, 125);
label2.Text = "Selamat datang di Selling System.";
label2.Location = new Point(600, 30);
label3.Text = "Banyaknya:";
label3.Location = new Point(145, 125);
label4.Text = "Keterangan:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total di Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total di Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total di Rp:";
label7.Location = new Point(1080, 580);
}
//****TextBox for Code****
for (int y = 0; y <= 16; y++)
{
textBoxCodeContainer.Add(new NumericTextBox());
textBoxCodeContainer[y].Size = new Size(100, 50);
textBoxCodeContainer[y].Location = new Point(25, 150 + (y * 25));
textBoxCodeContainer[y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
textBoxCodeContainer[y].AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxCodeContainer[y].AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxCodeContainer[y].AutoCompleteCustomSource = codesCollection;
theForm.Controls.Add(textBoxCodeContainer[y]);
}
//****TextBox for Quantity****
for (int y = 0; y <= 16; y++)
{
textBoxQuantityContainer.Add(new NumericUpDown());
textBoxQuantityContainer[y].Size = new Size(100, 50);
textBoxQuantityContainer[y].Location = new Point(125, 150 + (y * 25));
textBoxQuantityContainer[y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
textBoxQuantityContainer[y].Maximum = 1000;
theForm.Controls.Add(textBoxQuantityContainer[y]);
}
//****TextBox for Description****
for (int y = 0; y <= 16; y++)
{
textBoxDescContainer.Add(new TextBox());
textBoxDescContainer[y].Size = new Size(750, 50);
textBoxDescContainer[y].Location = new Point(225, 150 + (y * 25));
theForm.Controls.Add(textBoxDescContainer[y]);
}
//****TextBox for Sub Total****
for (int y = 0; y <= 16; y++)
{
textBoxSubTotalContainer.Add(new TextBox());
textBoxSubTotalContainer[y].Size = new Size(175, 50);
textBoxSubTotalContainer[y].Location = new Point(975, 150 + (y * 25));
theForm.Controls.Add(textBoxSubTotalContainer[y]);
}
//****TextBox for Total****
for (int y = 0; y <= 16; y++)
{
textBoxTotalContainer.Add(new TextBox());
textBoxTotalContainer[y].Size = new Size(175, 50);
textBoxTotalContainer[y].Location = new Point(1150, 150 + (y * 25));
textBoxTotalContainer[y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
theForm.Controls.Add(textBoxTotalContainer[y]);
}
//****TextBox for Total All****
textBoxAllTotalContainer.Size = new Size(175, 50);
textBoxAllTotalContainer.Location = new Point(1150, 575);
textBoxAllTotalContainer.TextChanged += new System.EventHandler(this.textBox_TextChanged);
theForm.Controls.Add(textBoxAllTotalContainer);
}
private void UpdateDatas()
{
int codeValue = 0;
int index = 0;
string query = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] IN (";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
for (int i = 1; i < 17; i++)
{
if (int.TryParse(this.textBoxCodeContainer[i].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[index].TextLength != 0)
{
this.textBoxQuantityContainer[index].Maximum = Convert.ToInt32(dReader["Quantity"].ToString());
this.textBoxDescContainer[index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[index].Text = dReader["Price"].ToString();
}
index += 1;
}
dReader.Close();
conn.Close();
}
private void UpdatePrice()
{
int totalPrice = 0;
int quantity = 0;
int price = 0;
for (int i = 0; i < 17; i++)
{
if (textBoxQuantityContainer[i].Value > 0)
{
quantity = (int)textBoxQuantityContainer[i].Value;
price = Convert.ToInt32(textBoxSubTotalContainer[i].Text);
textBoxTotalContainer[i].Text = (quantity * price).ToString();
}
else
{
textBoxSubTotalContainer[i].Text = "";
textBoxTotalContainer[i].Text = "";
}
}
for (int i = 0; i < 17; i++)
{
if (textBoxTotalContainer[i].TextLength != 0)
{
totalPrice += Convert.ToInt32(textBoxTotalContainer[i].Text);
}
}
textBoxAllTotalContainer.Text = totalPrice.ToString("n2");
}
private void UpdateQuantity()
{
int index = 0;
int codeValue = 0;
decimal newVal;
List<int> integers = new List<int>();
foreach (var tb in textBoxCodeContainer)
{
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}
string command = "UPDATE [Seranne] SET [Quantity]=? WHERE [Code] IN(" + string.Join(", ", integers) + ")";
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(command, conn);
cmd.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters["Quantity"].Value = this.newVal.ToString();
OleDbDataReader dReader;
conn.Open();
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0)
{
newVal = (Convert.ToInt32(dReader["Quantity"].ToString()) -
textBoxQuantityContainer[index].Value);
int numberOfRows = cmd.ExecuteNonQuery();
}
index += 1;
}
if (newVal == 0)
{
System.Media.SoundPlayer sounds = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sounds.Play();
MessageBox.Show("Cannot Update", "Error");
}
else
{
System.Media.SoundPlayer sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
sound.Play();
MessageBox.Show("Was Updated Successfully", "Success");
}
dReader.Close();
conn.Close();
}
private void textBox_TextChanged(object sender, EventArgs e)
{
UpdateDatas();
UpdatePrice();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateQuantity();
}
Thanks a bunch
Good day, i got several things here:
1) cmd.Parameters["Quantity"].Value = this.newVal.ToString(); conversion to string is not needed here, because the Value is an object. You already defined that it should be handled as integer.
2) Replace the ? within you query to #Quantity, so it will be filled by the query execution.
3) When updating you don't need to execute it as a reader. use the int numberOfRows = cmd.ExecuteNonQuery(); without the loop. It will update all items.
4) You should execute the if (textBoxQuantityContainer[index].Value != 0 && textBoxQuantityContainer[index].Value >=
Convert.ToInt32(dReader["Quantity"].ToString()))
{ when building the integers list, this way you are only updating the right quantities.
If you only want to update certain rows, you'll have to expand your where clause:
cmd.Parameters.Add("MinimumQuantity", System.Data.OleDb.OleDbType.Integer).Value = minimumQuantity;
string command = "UPDATE [Seranne]
SET [Quantity]=#Quantity
WHERE [Code] IN(" + string.Join(", ", integers) + ")
AND [Quantity] > #MinimumQuantity
The higest risk is: You assume that the order and count of the records are the same between your textBoxCodeContainer and the database.
What is the relation between a textbox and a row. How do you know what textbox links to which row?
I could give you a push in the right direction, if you show me some more code (like where/how is textBoxCodeContainer defined)
UPDATE:
I made some code the read and manipulate your database, this is not tested since i don't have any database here.
I would create these classes, 1 is a data class Product and one is a Handler class ProductHandler.
The data class only contains the data (not in presentation format) The data handler knows how to read and write them.
public class Product
{
public int Code { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
}
public class ProductHandler
{
public ProductHandler(string connectionString)
{
ConnectionString = connectionString;
}
public bool AddProduct(Product product)
{
return AddProducts(new Product[] { product }) > 0;
}
public int AddProducts(IEnumerable<Product> products)
{
int rowsInserted = 0;
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
string query = "INSERT INTO [Seranne] (Code, Description, Quantity) VALUES(#Code, #Description, #Quantity)";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("Code", OleDbType.Integer);
cmd.Parameters.Add("Description", OleDbType.VarChar);
cmd.Parameters.Add("Quantity", OleDbType.Integer);
foreach (var product in products)
{
cmd.Parameters["Code"].Value = product.Code;
cmd.Parameters["Description"].Value = product.Description;
cmd.Parameters["Quantity"].Value = product.Quantity;
rowsInserted += cmd.ExecuteNonQuery();
}
}
}
return rowsInserted;
}
public bool UpdateProduct(Product product)
{
return UpdateProducts(new Product[] { product }) > 0;
}
public int UpdateProducts(IEnumerable<Product> products)
{
int rowsUpdated = 0;
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
string query = "UPDATE [Seranne] SET Description = #Description, Quantity = #Quantity WHERE [Code] == #Code)";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("Code", OleDbType.Integer);
cmd.Parameters.Add("Description", OleDbType.VarChar);
cmd.Parameters.Add("Quantity", OleDbType.Integer);
foreach (var product in products)
{
cmd.Parameters["Code"].Value = product.Code;
cmd.Parameters["Description"].Value = product.Description;
cmd.Parameters["Quantity"].Value = product.Quantity;
rowsUpdated += cmd.ExecuteNonQuery();
}
}
}
return rowsUpdated;
}
public bool DeleteProduct(Product product)
{
return DeleteProducts(new int[] { productCode }) > 0;
}
public int DeleteProducts(IEnumerable<Product> products)
{
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
string productCodeStr = string.Join(", ", products.Select(item => item.Code));
string query = string.Format("DELETE FROM [Seranne] WHERE [Code] in ({0})", productCodeStr);
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
int rowsDeleted = cmd.ExecuteNonQuery();
return rowsDeleted;
}
}
}
public IEnumerable<Product> ReadAllProducts()
{
List<Product> result = new List<Product>();
using (OleDbConnection conn = new OleDbConnection(ConnectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT [Code], [Description], [Quantity] FROM [Seranne]", conn))
using (OleDbDataReader dReader = cmd.ExecuteReader())
while (dReader.Read())
{
Product product = new Product();
product.Code = Convert.ToInt32(dReader["Code"]);
product.Description = Convert.ToString(dReader["Description"]);
product.Quantity = Convert.ToInt32(dReader["Quantity"]);
result.Add(product);
}
}
return result;
}
public string ConnectionString { get; private set; }
}
Some example code:
ProductHandler _productHandler = new ProductHandler("connectionstring here or from config");
public void Example()
{
_productList.Clear();
_productList.AddRange(_productHandler.ReadAllProducts());
// displaying
foreach (var product in _productList)
Trace.WriteLine(string.Format("code: {0}, description: {1}, quantity: {2}", product.Code, product.Description, product.Quantity);
// updating
var selectedProduct = _productList.FirstOrDefault(item => item.Code == 15);
if(selectedProduct!= null)
{
selectedProduct.Quantity = 50;
_productHandler.UpdateProduct(selectedProduct);
}
// deleting
_productHandler.DeleteProducts(_productList.Where(item => item.Quantity < 5));
}
How to link the textboxes to the right product:
I would create a UserControl that contains a Product property and the TextBoxes and handles when textbox_changed events occurs. Those event handlers manipulate the Product instance.
You only generate 16 controls and bind a product to it. When you press a button, you only need to save the changed products.

where I am wrong? creating labels dynamically c#

I created labels and textboxes dynamically . everything goes fine,but the second label doesn't want to appear at all. where i am wrong? this is my code in C#:
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
OracleDataReader reader;
int x = 434;
int y = 84;
int i = 0;
try
{
conn.Open();
foreach (var itemChecked in checkedListBox1.CheckedItems)
{
Label NewLabel = new Label();
NewLabel.Location = new Point(x + 100, y);
NewLabel.Name = "Label" + i.ToString();
Controls.Add(NewLabel);
TextBox tb = new TextBox();
tb.Location = new Point(x, y);
tb.Name = "txtBox" + i.ToString();
Controls.Add(tb);
y += 30;
OracleCommand cmd = new OracleCommand("SELECT distinct data_type from all_arguments where owner='HR' and argument_name='" + itemChecked.ToString() + "'", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label[0].Text = reader["data_type"].ToString();
}
i++;
}
}
finally
{
if (conn != null)
conn.Close();
}
}
private void Procedure()
{
string proc = "";
try
{
conn.Open();
if (this.listView1.SelectedItems.Count > 0)
proc = listView1.SelectedItems[0].Text;
OracleCommand cmd = new OracleCommand("" + proc + "", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
int i = 0;
foreach (var itemChecked1 in checkedListBox1.Items)
{
Control[] txt = Controls.Find("txtBox" + i.ToString(), false);
Control[] label = Controls.Find("Label" + i.ToString(), false);
cmd.Parameters.Add(new OracleParameter("select distinct data_type from all_arguments where owner='HR' and argument_name=toupper("+itemChecked1.ToString()+")",conn));
cmd.Parameters[":"+itemChecked1.ToString()+""].Value=label[0].Text;
cmd.Parameters.Add(new OracleParameter(":" + itemChecked1.ToString() + "", OracleDbType.Varchar2));
cmd.Parameters[":" + itemChecked1.ToString() + ""].Value = txt[0].Text;
i++;
I think the second Label has appeared. But its text is an empty string! So you will never see it.
Check the "data_type" returned by DB reader.

Categories

Resources