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.
Related
**Hello everyone, im fairly new with c# and am currently trying to make flappy bird in c# windows form application. I am trying to make a leaderboard. I want to save the highscores into a mysql database. But i dont know how to compare the score you get in game with the data in the database. The query works but i dont know how to get that result and assign that to the variable "lastleaderboardscore". Would you guys be able to help?
Thank you**
public partial class Form1 : Form
{
int pipeSpeed = 8;
int groundspeed;
int gravity = 8;
int score = 0;
int lives = 3;
int totalScore = 0;
private int tableOf = 5; //preset for the table of 5
int lastleaderboardscore;
int i;
Random rndHeight = new Random();
{
InitializeComponent();
string server = "localhost";
string database = "flappyLeader";
string dbUsername = "root";
string dbPassword = "";
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + dbUsername + ";" + "PASSWORD=" + dbPassword + ";";
MySqlConnection mysqlcon = new MySqlConnection(connectionString);
i = 0;
mysqlcon.Open();
MySqlCommand cmd = mysqlcon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select score from leaderboard order by Score desc limit 1 offset 9";
DataTable dtbl = new DataTable();
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
i = Convert.ToInt32(dtbl.Rows.Count.ToString());
lastleaderboardscore = ds.Tables[0].Rows[2].;
mysqlcon.Close();
Here you'll find the code where I compare the 2 variables "totalscore" (score in game) and "lastleaderboardscore"
if (lives == 0)
{
if (totalScore > lastleaderboardscore)
{
/* TextBox1.Show();*/
}
label4.Show();
label4.Text = "your total score is" + totalScore.ToString();
lives = 3;
pipeSpeed = 8;
label1.Text = "game Over";
totalScore = 0;
label3.Visible = false;
}
You can use datatable itself to get the result.
SqlCommand command = new SqlCommand(""Select score from leaderboard order by Score desc limit 1 offset 9", mysqlcon);
DataTable dtbl = new DataTable();
MySqlDataAdapter sda = new MySqlDataAdapter(command);
sda.Fill(dtbl);
lastleaderboardscore =dtbl.Rows(0).Item(0).ToString
This is the basic idea.
Hello everyone : I'm creating an ASP.net project, here is the folder with a problem :
Dashboard :
--> DashboardIndex.cshtml
--> DashboardPage.cs
--> DashboardPageModel.cs
My page generates the following code
<div class="small-box bg-aqua">
<div class="inner">
<h3>#Model.OpenOrders</h3>
<p>Open Orders</p>
</div>
<div class="icon">
<i class="ion ion-bag"></i>
</div>
More info <i class="fa fa-arrow-circle-right"></i>
</div>
I click on the button, what leads me to http://localhost:21739/IP/1/11_2
Aaand.. Error 404 !
Yet, I coded what seems to be the appropriate function (I compared with another function I code (which works) and I didn't find any relevant differences)
namespace Serene7.Common.Pages
{
using Serenity;
using System;
using System.Linq;
using Serenity.Data;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI;
using System.Web.UI.WebControls;
[RoutePrefix("Dashboard"), Route("{action=index}")]
public class DashboardController : Controller
{
[Authorize, HttpGet, Route("~/")]
public ActionResult Index()
{
return View(MVC.Views.Common.Dashboard.DashboardIndex, new DashboardPageModel());
}
[HttpGet]
[Route("IP/{Station=0}/{Timestp=0}")]
public ActionResult IP(int station, string timestp)
{
timestp = timestp.Replace("_", ":");
SqlConnection myConn = new SqlConnection(#"Server=(LocalDb)\MSSqlLocalDB;Integrated security=SSPI;database=Serene7_Default_v1");
List<string> listeIps = new List<string>();
string listDb = string.Format("SELECT DISTINCT (IpSource) FROM [Serene5_Default_v1].[tcpdump].[TCPDump] WHERE Station = '{0}' AND TimeStp = '{1}';",station,timestp);
SqlCommand myCommand = new SqlCommand(listDb, myConn);
string listDb2 = string.Format("SELECT DISTINCT (IpSource,IpDestination) FROM [Serene5_Default_v1].[tcpdump].[TCPDump] WHERE Station = '{0}' AND TimeStp = '{1}';", station, timestp);
SqlCommand myCommand2 = new SqlCommand(listDb2, myConn);
myConn.Open();
SqlDataReader reader = myCommand.ExecuteReader();
while (reader.Read())
{
listeIps.Add(reader[0].ToString());
}
reader.Close();
SqlDataReader reader2 = myCommand.ExecuteReader();
while (reader2.Read())
{
listeIps.Add(reader2[0].ToString());
}
List<string> noRepetitions = listeIps.Distinct().ToList();
int lengthList = noRepetitions.Count;
byte[] imageBuffer = new byte[400 * lengthList * lengthList * 4];
string listDb3 = string.Format("SELECT SUM(ToTheRight) FROM [Serene5_Default_v1].[tcpdump].[TCPDump] WHERE IdSource = #IdSource AND IdDestination = #IdDestination AND Station = '{0}' AND TimeStp = '{1}';", station, timestp);
string listDb4 = string.Format("SELECT SUM(ToTheLeft) FROM [Serene5_Default_v1].[tcpdump].[TCPDump] WHERE IdDestination = #IdSource AND IdSource = #IdDestination AND Station = '{0}' AND TimeStp = '{1}';", station, timestp);
SqlCommand myCommand3 = new SqlCommand(listDb3, myConn);
SqlCommand myCommand4 = new SqlCommand(listDb4, myConn);
IDbDataParameter param;
param = myCommand3.CreateParameter();
param.ParameterName = "#IdDestination";
param.Value = "''";
param = myCommand3.CreateParameter();
param.ParameterName = "#IdSource";
param.Value = "''";
param = myCommand4.CreateParameter();
param.ParameterName = "#IdDestination";
param.Value = "''";
param = myCommand4.CreateParameter();
param.ParameterName = "#IdSource";
param.Value = "''";
int[,] matrix = new int[lengthList, lengthList];
for (int x = 0; x < lengthList; x++)
{
for (int y = 0; y < lengthList; y++)
{
myCommand3.Parameters["#IdSource"].Value = "'" + noRepetitions[x] + "'";
myCommand3.Parameters["#IdDestination"].Value = "'" + noRepetitions[y] + "'";
myCommand4.Parameters["#IdSource"].Value = "'" + noRepetitions[x] + "'";
myCommand4.Parameters["#IdDestination"].Value = "'" + noRepetitions[y] + "'";
int total = 0;
SqlDataReader reader3 = myCommand3.ExecuteReader();
SqlDataReader reader4 = myCommand4.ExecuteReader();
while (reader3.Read())
{
total += (int)reader[0];
}
reader3.Close();
while (reader4.Read())
{
total += (int)reader[0];
}
reader4.Close();
matrix[x, y] = total;
}
}
int maximum = matrix.Cast<int>().Max();
double logMax = Math.Log(maximum);
for (int x = 0; x < 20 * lengthList; x++)
{
for (int y = 0; y < 20 * lengthList; y++)
{
int posX = x % 20;
int posY = y % 20;
int offset = ((20 * lengthList * 4) * y) + (x * 4);
int test = 0;
if (matrix[x, y] > 0)
{
test = 1;
}
int value = (int)(test * (10 + (245 * Math.Log(matrix[x, y]) / logMax)));
imageBuffer[offset] = (byte)value;
imageBuffer[offset + 1] = (byte)value;
imageBuffer[offset + 2] = (byte)value;
imageBuffer[offset + 3] = 255;
}
}
unsafe
{
fixed(byte* ptr = imageBuffer)
{
using (Bitmap image = new Bitmap(256, 100, 256 * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(#"C:\Users\FS091843\Desktop\Stations\Station1\greyscale.png");
}
}
}
DashboardPageModel dashboard = new DashboardPageModel();
return View(MVC.Views.Common.Dashboard.DashboardIndex, dashboard);
}
}
}
Anyone has an idea of what is going wrong ?
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);
}
}
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 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.