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);
}
}
Related
Good Day.
I have a stock list in mysql database
I then have a windows form where i can allocate stock to a certain job, i do this by pulling all from my parts list in mysql and checking if the item selected by the user is in stock, i then add that item to a list using listbox.Items.Add(myitem). In also ass the quantity the user wants to a different list.
When I allocate the stock to a job i create one string separated by ',' and store that to mysql and the same with my quantites resulting is a parts string that looks like: 'PART001,PART002,PART003' and my quantities like: '2,1,3'.
I then add that to a request list which the admin needs to approve.
My problem comes in where the request form is loaded, I pull these parts and quantity lists from mySql and split them wit myString.Split(',');
And I then just add them to another listbox, HOWEVER when i get the quantities that my stock table has available, I loop over the part numbers and pull the quantities but if I for example have my first part as item 3 in my stock table and my second item as my 1st item in my stock list, it will assign item 1's quantity to my item 3. So basically my loop does not assign the right values.
Here is my code for checking the values
ListBox lb = PartsListBox;
ListBox lbq = PartsQuanListBox;
String query = "SELECT * FROM parts WHERE partnum = '"+PartsSelectCb.Text.Trim()+"'";
String partnum = "N/A";
int quan = 0;
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
partnum = (String)dr["partnum"];
}
con.Close();
if(PartsSelectCb.Text == partnum)
{
quan = int.Parse(textBox1.Text);
if (quan > 0)
{
if (!lb.Items.Contains(PartsSelectCb.Text.Trim()))
{
lb.Items.Add(PartsSelectCb.Text.Trim());
lbq.Items.Add(textBox1.Text.Trim());
}
}
}
And here is my code for inserting those values into my request table
private void SendRequest()
{
String dte = DateTime.Now.ToShortDateString();
String g = "";
String h = "";
String a = "";
String b = "";
if (PartsListBox.Items.Count > 0)
{
foreach (var item in PartsListBox.Items)
{
g += item.ToString() + ",";
}
h = g.Substring(0, g.Length - 1);
}
if (PartsQuanListBox.Items.Count > 0)
{
foreach (var itemt in PartsQuanListBox.Items)
{
a += itemt.ToString() + ",";
}
b = a.Substring(0, a.Length - 1);
}
String query = "INSERT INTO partsbook VALUES (NULL,'" + h + "','" + b + "','"
+ ReqTxt.Text.Trim() + "','" + userN + "','" + dte + "','" +""+"','"+ "REQUEST" + "')";
MySqlConnection dataCon = new MySqlConnection(conString);
dataCon.Open();
MySqlCommand cmd = new MySqlCommand(query, dataCon);
try
{
cmd.ExecuteNonQuery();
pmf.CheckRequests();
this.Close();
}
catch (Exception r)
{
MessageBox.Show("ERROR :" + r.Message.ToString());
}
dataCon.Close();
MessageBox.Show("REQUEST SENT");
this.Close();
}
Then on the request side
private void GetStock()
{
String query = "SELECT * FROM parts";
String qtys = "";
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String nme = (String)dr["partnum"];
foreach(var item in UPartsListBox.Items)
{
if(item.ToString() == nme)
{
int q = (int)dr["qty"];
qtys += q.ToString() + ",";
}
}
}
con.Close();
string[] words = qtys.Split(',');
foreach(var word in words)
{
if(word != "")
{
SPartsQuanListBox.Items.Add(word);
}
}
}
User Request:
Admin View:
Stock Table:
Okay, so i'm trying to get 18 "prices" from my database in SQL, then setting them in a local array. So far i have this logic in the data retrieval:
private void dbPrices()
{
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=phvpos";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
for (int i = 1; i < 19; i++)
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT price from products where id = '" + i + "'";
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
pr[i] = reader.ToString();
prods[i] = int.Parse(pr[i]);
}
}
}
And this logic in getting the total amount:
private void btnTotal_Click(object sender, EventArgs e)
{
dbPrices();
itemcost[0] = Convert.ToInt32(txtRice.Text) * prods[0];
itemcost[1] = Convert.ToInt32(txtAdobo.Text) * prods[1];
itemcost[2] = Convert.ToInt32(txtIgado.Text) * prods[2];
itemcost[3] = Convert.ToInt32(txtSisig.Text) * prods[3];
...
itemcost[18] = itemcost[0] + itemcost[1] + itemcost[2] + itemcost[3] + itemcost[4] + itemcost[5]
+ itemcost[6] + itemcost[7] + itemcost[8] + itemcost[9] + itemcost[10]
+ itemcost[11] + itemcost[12] + itemcost[13] + itemcost[14] + itemcost[15]
+ itemcost[16] + itemcost[17];
int totalPrice = itemcost[18];
lblTotal.Text = Convert.ToString(totalPrice);
}
this line in dbPrices() spits out a 'input string was not in a correct format' error:
while (reader.Read())
{
pr[i] = reader.ToString();
prods[i] = int.Parse(pr[i]);
}
I have also tried:
while (reader.Read())
{
prods[i] = Convert.toInt32(reader.ToString());
}
But also spits the same error. Is there anything that i'm doing wrong?
Try this. I find that when using 'reader' that even when your query only grabs one value you still need to specify what value your looking for.
prods[i] = int.Parse(reader["price"]);
and if price is nullable in the database use a ternary operator
prods[i] = reader["price"] == DBNull.Value ? 0 : int.parse(reader["price"]);
The value from your result needs to convert to int and your for loop block might cause you serious problem in the future, you might want to have a projection query and then assign the values of the result.
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = $"SELECT price FROM products WHERE id BETWEEN 1 AND 18"; //use projection. if you have a dynamic product id set, you can use IN in query.
MySqlDataReader reader = cmd.ExecuteReader();
var counter = 0; //counter
while (reader.Read())
{
prods[counter] = Convert.ToInt32(reader["price"]); //convert the result first then assign it to the item.
counter++;
}
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);
}
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);
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.