Select Data from Database Depend on Items in Listbox c# - c#

I have a problem to select data depending on all items in a Listbox. Here, in my Listbox there are two items, named Kamera125 and Kamera127. Kamera125 and Kamera127 exist in a MS Access Database. So, when I run my program, I want my program to select Kamera125 and Kamera127 from listbox that connected to MS Access. I used the following query
string selectsemuakoordgaris = "select * from koordinatgaris where namakamera='" + listBox3.Text + "'";
and it doesn't work.
These is my codes :
private void ProsesSemuaKamera()
{
Stopwatch watch = Stopwatch.StartNew();
Ping ping = new Ping();
PingReply pingreply;
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();
kon.Open();
string selecturl = "select * from datakamera";
command.CommandText = selecturl;
OleDbDataReader bacadata = command.ExecuteReader();
while (bacadata.Read())
{
int counturl = 0;
pingreply = ping.Send(bacadata["ipadd"].ToString());
if (pingreply.Status == IPStatus.Success)
{
listBox1.Items.Add(bacadata["ipadd"].ToString());
listBox3.Items.Add(bacadata["namakamera"].ToString());
textBox1.Text += bacadata["namakamera"].ToString() + Environment.NewLine;
CaptureSemuaKamera = new Capture(bacadata["urlkamera"].ToString());
Application.Idle += new EventHandler(ProcessFrameSemuaKamera);
}
else if (pingreply.Status != IPStatus.Success)
{
listBox2.Items.Add(bacadata["ipadd"].ToString());
}
}
kon.Close();
watch.Stop();
File.AppendAllText(#"D:\Dokumen\Alfon\TA Alfon\Waktu Eksekusi Ping.txt", "Waktu eksekusi ping " + DateTime.Now + " :" + " " + watch.Elapsed.TotalMilliseconds.ToString() + Environment.NewLine);
}
private void ProcessFrameSemuaKamera(object sender, EventArgs e)
{
Image<Bgr, Byte> sourceImage = CaptureSemuaKamera.QueryFrame();
SourceBox.Image = sourceImage.Bitmap;
ProsesSemuaKamera();
}
private void ProsesKameraSemua()
{
Image<Bgr, Byte> sourceImage = CaptureSemuaKamera.QueryFrame();
SourceBox.Image = sourceImage.Bitmap;
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand commandkoord = kon.CreateCommand();
OleDbCommand commandkoordgaris = kon.CreateCommand();
kon.Open();
string selectsemuakoord = "select * from koordinatkotak where namakamera='"+ listBox3.Items + "'";
string selectsemuakoordgaris = "select * from koordinatgaris where namakamera='" + listBox3.Items + "'";
commandkoord.CommandText = selectsemuakoord;
commandkoordgaris.CommandText = selectsemuakoordgaris;
OleDbDataReader bacakoord = commandkoord.ExecuteReader();
OleDbDataReader bacakoordgaris = commandkoordgaris.ExecuteReader();
while (bacakoord.Read() && bacakoordgaris.Read())
{
#region Perspective projection
PointF[] srcs = new PointF[4];
srcs[0] = new PointF(int.Parse(bacakoord["x1source"].ToString()), int.Parse(bacakoord["y1source"].ToString())); //119, 187
srcs[1] = new PointF(int.Parse(bacakoord["x2source"].ToString()), int.Parse(bacakoord["y2source"].ToString())); //242, 181
srcs[2] = new PointF(int.Parse(bacakoord["x3source"].ToString()), int.Parse(bacakoord["y3source"].ToString())); //253, 225
srcs[3] = new PointF(int.Parse(bacakoord["x4source"].ToString()), int.Parse(bacakoord["y4source"].ToString())); //112, 231
PointF[] dsts = new PointF[4];
dsts[0] = new PointF(int.Parse(bacakoord["x1proj"].ToString()), int.Parse(bacakoord["y1proj"].ToString()));
dsts[1] = new PointF(int.Parse(bacakoord["x2proj"].ToString()), int.Parse(bacakoord["y2proj"].ToString()));
dsts[2] = new PointF(int.Parse(bacakoord["x3proj"].ToString()), int.Parse(bacakoord["y3proj"].ToString()));
dsts[3] = new PointF(int.Parse(bacakoord["x4proj"].ToString()), int.Parse(bacakoord["y4proj"].ToString()));
HomographyMatrix mywarpmat = CameraCalibration.GetPerspectiveTransform(srcs, dsts);
Image<Bgr, Byte> newImage = sourceImage.WarpPerspective(mywarpmat, 355, 288, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR, Emgu.CV.CvEnum.WARP.CV_WARP_FILL_OUTLIERS, new Bgr(0, 0, 0));
Image<Gray, Byte> newImageGray = newImage.Convert<Gray, Byte>();
Image<Bgr, Byte> imageToShow = newImage.Copy();
Image<Bgr, Byte> imageToShowGaris = newImage.Copy();
ProjectionBox.Image = newImage.Bitmap; //I want to show Projection result in ProjectionBox. All of coordinates are saved in database. When Kamera125 is choosen, all of coordinates in Kamera125 will be executed. So here, I want to execute all of coordinates of Kamera125 and Kamera127 that is shown in listBox.
#endregion
}
kon.Close();
}

here's a simple method where you can pass in your listbox that has the items selected. It will return a string of the where clause built from the selected items.
private string BuildWhereClause(ListBox lb)
{
string WHEREclause = string.Empty;
foreach(var itm in lb.SelectedItems)
{
if (WHEREclause == string.Empty )
{
WHEREclause += " WHERE namakamera = '" + itm + "' ";
}
else
{
WHEREclause += " OR namakamera = '" + itm + "' ";
}
}
return WHEREclause;
}
From this you can build your statement
string selectsemuakoord = "select * from koordinatkotak " + BuildWhereClause(YourListBox);

Related

Plotting several lines in a Chart

I have 4 radio buttons. Each one of them corresponds to one type (columns in the DB) of the input temperature that I wanna use.
What do I already have:
If I choose one radio button + press Load - it plots the graph. If I choose again this button (or any of the other Radiobuttons) it plots in a sequence of the original graph.
What do I need help with:
I would like that each time that I press the button "Load" the Line would be "added" to the existing graph. In other words, I may have 4 different lines in the same graph, each one representing on radio button that I selected and pressed "Load."
Code:
private void BtnLoadDataToGraph_Click(object sender, EventArgs e)
{
string column_to_use = "";
double column_percentage_XX = 0;
double column_percentage_XX = 0;
string ReceiveNameFile = CboxReceiveNameFile.Text;
if (RadioButtonStartXXTemp.Checked)
column_to_use = "START_XX_TEMP";
else if (RadioButtonStartXXTemp.Checked)
column_to_use = "START_XX_TEMP";
if (RadioButtonAvgTemp.Checked)
column_to_use = "(START_XX_TEMP + START_XX_TEMP)/2";
else
{
column_percentage_XX = Int32.Parse(TextBoxXXPercentage.Text);
column_percentage_XX = (Convert.ToDouble(column_percentage_XX) / 100);
column_percentage_XX = Int32.Parse(TextBoxXXPercentage.Text);
column_percentage_XX = (Convert.ToDouble(column_percentage_XX) / 100);
column_to_use = "(START_XX_TEMP*" + column_percentage_XX + ")+(START_XX_TEMP*" + column_percentage_XX + ")";
}
SqlConnection conDatabase = new SqlConnection("XXXXXX");
SqlCommand cmdDatabase = new SqlCommand("select " + column_to_use + " AS temp, SUBSTRING (header.TIME,CHARINDEX(' ',header.TIME,1),len(header.TIME)) as time,CONVERT(datetime,header.TIME,101) as new_time, REVERSE(SUBSTRING(REVERSE(fnames.PATH_NAME),0,CHARINDEX('\\\',REVERSE(fnames.PATH_NAME)))) as folder_name from TBL_DATA_TYPE_RO_HEADER header,TBL_FILE_NAMES fnames,TBL_PROGRAM program where program.PK_ID_TBL_PROGRAM = fnames.FK_ID_TBL_PROGRAM and fnames.PK_ID_TBL_FILE_NAMES = header.FK_ID_TBL_FILE_NAMES and REVERSE(SUBSTRING(REVERSE(fnames.PATH_NAME),0,CHARINDEX('\\\',REVERSE(fnames.PATH_NAME))))='" + ReceiveNameFile + "' order by new_time", conDatabase);
SqlDataReader myReader;
try
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
this.ChartTempVsTime.Series["TimeVsTemp"].Points.AddXY(myReader["time"].ToString(), myReader["temp"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any ideas of how can I do this? I was thinking in maybe use "Points.Aggregate" instead of "Points.AddXY". But I don't think that it is the right path especially because each radiobutton should has a different color line.
Any help or tips are welcome!
Just create a new series in the chart and add the new points into it
this.ChartTempVsTime.Series["TimeVsTemp"].Points.AddXY(myReader["time"].ToString(), myReader["temp"].ToString());
This line is always plotting your data on the same series. You need to make a new series each time you press the load button. Something like:
private void BtnLoadDataToGraph_Click(object sender, EventArgs e)
{
try
{
string column_to_use = "";
double column_percentage_XX = 0;
double column_percentage_XX = 0;
string ReceiveNameFile = CboxReceiveNameFile.Text;
if (RadioButtonStartXXTemp.Checked)
column_to_use = "START_XX_TEMP";
else if (RadioButtonStartXXTemp.Checked)
column_to_use = "START_XX_TEMP";
if (RadioButtonAvgTemp.Checked)
column_to_use = "(START_XX_TEMP + START_XX_TEMP)/2";
else
{
column_percentage_XX = Int32.Parse(TextBoxXXPercentage.Text);
column_percentage_XX = (Convert.ToDouble(column_percentage_XX) / 100);
column_percentage_XX = Int32.Parse(TextBoxXXPercentage.Text);
column_percentage_XX = (Convert.ToDouble(column_percentage_XX) / 100);
column_to_use = "(START_XX_TEMP*" + column_percentage_XX + ")+(START_XX_TEMP*" + column_percentage_XX + ")";
}
SqlConnection conDatabase = new SqlConnection("XXXXXX");
SqlCommand cmdDatabase = new SqlCommand("select " + column_to_use + " AS temp, SUBSTRING (header.TIME,CHARINDEX(' ',header.TIME,1),len(header.TIME)) as time,CONVERT(datetime,header.TIME,101) as new_time, REVERSE(SUBSTRING(REVERSE(fnames.PATH_NAME),0,CHARINDEX('\\\',REVERSE(fnames.PATH_NAME)))) as folder_name from TBL_DATA_TYPE_RO_HEADER header,TBL_FILE_NAMES fnames,TBL_PROGRAM program where program.PK_ID_TBL_PROGRAM = fnames.FK_ID_TBL_PROGRAM and fnames.PK_ID_TBL_FILE_NAMES = header.FK_ID_TBL_FILE_NAMES and REVERSE(SUBSTRING(REVERSE(fnames.PATH_NAME),0,CHARINDEX('\\\',REVERSE(fnames.PATH_NAME))))='" + ReceiveNameFile + "' order by new_time", conDatabase);
SqlDataReader myReader;
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
Series s = new Series();
while (myReader.Read())
{
s.Points.AddXY(myReader["time"].ToString(), myReader["temp"].ToString());
}
chart1.Series.Add(s);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

What's the best way to multithread?

I've got a little problem with my application.
I have a database editor that hangs up sometimes when I try to update the database file. Not every time, but pretty often, and every time it happens right before any changes are made to the database. I figured it's because of not using multithreading. I've only started learning programming recently though, and I'm kind of lost even after reading through a few multithreading explanations. Could someone explain to me how should I implement it in my specific example?
private void adjustStatsButton_Click(object sender, EventArgs e)
{
ReadWrite.AdjustStats(winnerInput.Text, loserInput.Text);
winnerInput.Text = "";
loserInput.Text = "";
Refresh(leaderboardBox);
}
public class ReadWrite
{
public static void AdjustStats(string winner, string loser)
{
SQLiteConnection dbConnection = new SQLiteConnection("Data Source = Leaderboards.sqlite; Version = 3");
string sql = "SELECT * FROM leaderboard WHERE name='" + winner + "'";
SQLiteCommand command = new SQLiteCommand(sql, dbConnection);
dbConnection.Open();
SQLiteDataReader reader = command.ExecuteReader();
double wrating = Convert.ToDouble(reader["rating"]);
int wmatches = Convert.ToInt32(reader["matches"]);
int wwins = Convert.ToInt32(reader["wins"]);
sql = "SELECT * FROM leaderboard WHERE name='" + loser + "'";
command = new SQLiteCommand(sql, dbConnection);
reader = command.ExecuteReader();
double lrating = Convert.ToDouble(reader["rating"]);
int lmatches = Convert.ToInt32(reader["matches"]);
int lwins = Convert.ToInt32(reader["wins"]);
int llosses = Convert.ToInt32(reader["losses"]);
double RC = (1 - ((wrating - lrating) / 200)) * 8;
if (RC < 0) RC *= -1;
if (RC < 4) RC = 4;
else if (RC > 12) RC = 12;
wmatches++;
wwins++;
lmatches++;
llosses++;
wrating += RC;
if (wrating < 0) wrating = 0;
lrating -= RC;
if (lrating < 0) lrating = 0;
double wwinrate = Convert.ToDouble(wwins) / wmatches;
double lwinrate = Convert.ToDouble(lwins) / lmatches;
sql = "UPDATE leaderboard SET rating=" + wrating + ", matches=" + wmatches + ", wins=" + wwins + ", winrate=" + wwinrate + " WHERE name='" + winner + "'";
command = new SQLiteCommand(sql, dbConnection);
command.ExecuteNonQuery();
sql = "UPDATE leaderboard SET rating=" + lrating + ", matches=" + lmatches + ", losses=" + llosses + ", winrate=" + lwinrate + " WHERE name='" + loser + "'";
command = new SQLiteCommand(sql, dbConnection);
command.ExecuteNonQuery();
dbConnection.Close();
}
}
The problem is that you are running the query in the UI thread. Here's an example for using the BackgroundWorker, heavily inspired from this example, and using Arguments. This way it will be running in a separate thread and it will not lock the GUI.
// Class for passing arguments
public class BqArguments
{
public string Winner {get;set}
public string Loser {get;set}
}
And your implementation:
BackgroundWorker _bw; // You need to initialize this somewhere.
private void adjustStatsButton_Click(object sender, EventArgs e)
{
// Maybe this should be initialized in ctor. But for this example we do it here...
_bw = new BackgroundWorker();
var arguments = new BqArguments
{
Winner = winnerInput.Text,
Loser = loserInput.Text
}
_bw.DoWork += bw_DoWork;
_bw.RunWorkerCompleted += bw_RunWorkerCompleted;
_bw.RunWorkerAsync(arguments);
}
private void bw_DoWork (object sender, DoWorkEventArgs e)
{
// Run your query in the background.
var arguments = e.Argument as BqArguments;
ReadWrite.AdjustStats(arguments.Winner, arguments.Loser);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// All done. Let's update the GUI.
winnerInput.Text = "";
loserInput.Text = "";
Refresh(leaderboardBox);
}
You just need to use async await keywords within your c# code and it will eventually lead Asynchronous calls to the DB I have made changes to your Code :
private async void adjustStatsButton_Click(object sender, EventArgs e)
{
await ReadWrite.AdjustStats(winnerInput.Text, loserInput.Text);
winnerInput.Text = "";
loserInput.Text = "";
Refresh(leaderboardBox);
}
public class ReadWrite
{
public static Task AdjustStats(string winner, string loser)
{
return Task.Run(() =>
{
SQLiteConnection dbConnection = new SQLiteConnection("Data Source = Leaderboards.sqlite; Version = 3");
string sql = "SELECT * FROM leaderboard WHERE name='" + winner + "'";
SQLiteCommand command = new SQLiteCommand(sql, dbConnection);
dbConnection.Open();
SQLiteDataReader reader = await command.ExecuteReaderAsync();
double wrating = Convert.ToDouble(reader["rating"]);
int wmatches = Convert.ToInt32(reader["matches"]);
int wwins = Convert.ToInt32(reader["wins"]);
sql = "SELECT * FROM leaderboard WHERE name='" + loser + "'";
command = new SQLiteCommand(sql, dbConnection);
reader = await command.ExecuteReaderAsync();
double lrating = Convert.ToDouble(reader["rating"]);
int lmatches = Convert.ToInt32(reader["matches"]);
int lwins = Convert.ToInt32(reader["wins"]);
int llosses = Convert.ToInt32(reader["losses"]);
double RC = (1 - ((wrating - lrating) / 200)) * 8;
if (RC < 0) RC *= -1;
if (RC < 4) RC = 4;
else if (RC > 12) RC = 12;
wmatches++;
wwins++;
lmatches++;
llosses++;
wrating += RC;
if (wrating < 0) wrating = 0;
lrating -= RC;
if (lrating < 0) lrating = 0;
double wwinrate = Convert.ToDouble(wwins) / wmatches;
double lwinrate = Convert.ToDouble(lwins) / lmatches;
sql = "UPDATE leaderboard SET rating=" + wrating + ", matches=" + wmatches + ", wins=" + wwins + ", winrate=" + wwinrate + " WHERE name='" + winner + "'";
command = new SQLiteCommand(sql, dbConnection);
await command.ExecuteNonQueryAsync();
sql = "UPDATE leaderboard SET rating=" + lrating + ", matches=" + lmatches + ", losses=" + llosses + ", winrate=" + lwinrate + " WHERE name='" + loser + "'";
command = new SQLiteCommand(sql, dbConnection);
await command.ExecuteNonQueryAsync();
dbConnection.Close();
}
});
}
The core of your problem is that you're calling blocking (synchronous) database calls on the UI thread. This blocks your UI thread while it's waiting for the database, instead of keeping it nicely responsive.
In the general case, since these are I/O-based operations, you should be able to make them naturally asynchronous, as per Lakhtey's answer. However, SQLite does not support actual asynchronous operations. :(
So, in this case, your best bet is to just wrap up the database work into a background thread. Note that using Task.Run is far superior to BackgroundWorker:
private async void adjustStatsButton_Click(object sender, EventArgs e)
{
await Task.Run(() => ReadWrite.AdjustStats(winnerInput.Text, loserInput.Text));
winnerInput.Text = "";
loserInput.Text = "";
Refresh(leaderboardBox);
}

multiple markers on gmap.net

Hi I have 1000 latitudes , longitudes and want to display all of them on maps .
I tried several ways to do it but not luck.....I have a datagridview which has client,lat,long,region. each client has a region.I have a combobox when I click on combobox region 1 it should display all clients on region 1 on map can it be possible. please help.
if (comboBox5.SelectedIndex == 0)//(REGION 1)
{
String Query = " SELECT top Latitude,Longitude FROM[ICPS].[dbo].[Sheet3_kir] ";
SqlCommand cmdDatabase = new SqlCommand(Query, conDatabase);
SqlDataReader myReader;
gMapControl1.MapProvider = GMap.NET.MapProviders.BingMapProvider.Instance;
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
GMapOverlay markersOverlay = new GMapOverlay("VCS MAP");
//gMapControl1.Overlays.Add(markersOverlay);
for (int i = 0; i <= dataGridView1.Rows.Count; i++)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var Latitude = double.Parse(dataGridView1.Columns[1].ToString());
var Longitude = double.Parse(dataGridView1.Columns[2].ToString());
gMapControl1.Position = new PointLatLng(Latitude, Longitude);
// GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(float.Parse(this.dataGridView1.Columns[1].ToString), float.Parse(this.textBox26.Text)),
// GMarkerGoogleType.green);
GMarkerGoogle m = new GMarkerGoogle(gMapControl1.Position, GMarkerGoogleType.green_pushpin);
//markersOverlay.Markers.Add(m);
}
}
MySqlDataAdapter da = new MySqlDataAdapter("select * from sinkhole where sinkhole_status = '" + "Active" + "'", Conn);
MySqlCommandBuilder cBuilder = new MySqlCommandBuilder(da);
DataTable dataTable = new DataTable();
DataSet ds = new DataSet();
da.Fill(dataTable);
for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
{
double lng = double.Parse(dataTable.Rows[i][4].ToString());
double lat = double.Parse(dataTable.Rows[i][3].ToString());
string location = dataTable.Rows[i][2].ToString();
string name = dataTable.Rows[i][1].ToString();
string desciption = dataTable.Rows[i][5].ToString();
GMapOverlay markersOverlay = new GMapOverlay(map, "marker");
GMapMarkerGoogleGreen marker = new GMapMarkerGoogleGreen(new PointLatLng(lat, lng));
markersOverlay.Markers.Add(marker);
//marker.ToolTipMode = MarkerTooltipMode.Always;
marker.ToolTip = new GMapRoundedToolTip(marker);
marker.ToolTipText = "Coordinates: (" + Convert.ToString(lat) + "," + Convert.ToString(lng) + ")" + "\nLocation: " + location + "\nName: " + name;
map.Overlays.Add(markersOverlay);
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
double lat = Convert.ToDouble(dataGridView1.Rows[i].Cells[9].Value) ;
double lng = Convert.ToDouble(dataGridView1.Rows[i].Cells[10].Value);
string Vehicle = Convert.ToString(dataGridView1.Rows[i].Cells[5].Value);
string name = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
string Adress = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
MapaContr.MapProvider = GMapProviders.GoogleHybridMap;
GMapOverlay markersOverlay = new GMapOverlay("markers");
GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(lat, lng), GMarkerGoogleType.lightblue);
markersOverlay.Markers.Add(marker);
marker.ToolTipMode = MarkerTooltipMode.Always;
marker.ToolTip = new GMapRoundedToolTip(marker);
marker.ToolTipText = "Adress: " + Adress + "\nIme: " + name + "\nVehicle:" + Vehicle ;
MapaContr.Overlays.Add(markersOverlay);
I am made solution for multiple markers on Gmap from MySql data base and datagridView(dataGridView1) solution. Its very precision and easy to manage.

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.

c# how to set beginInvoke end?

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.

Categories

Resources