MessageBox.Show(urls[m]);
of the code below it show 16 time like a,a,a,a,b,b,b,b,c,c,c,c,d,d,d,d how can i add 4 non duplicate to urls[m]. My code is purpose to swlwct url from data base to open on 4 different browser1 browser 2 .. but on browser show the same URL
namespace tabcontrolweb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT urlwebboard FROM `listweb` WHERE `urlwebboard` IS NOT NULL AND ( `webbordkind` = 'เว็บท้องถิ่น' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[4];
string thisrow = "";
string sumthisrow = "";
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = Reader.GetValue(i).ToString();
}
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
webBrowser1.Navigate(new Uri(urls[0]));
webBrowser1.Dock = DockStyle.Fill;
webBrowser2.Navigate(new Uri(urls[1]));
webBrowser2.Dock = DockStyle.Fill;
webBrowser3.Navigate(new Uri(urls[2]));
webBrowser3.Dock = DockStyle.Fill;
webBrowser4.Navigate(new Uri(urls[3]));
webBrowser4.Dock = DockStyle.Fill;
}
connection.Close();
}
I can't understand this code:
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
Why are you inserting in urls[m] the same value?
Bear in mind that in the previous loop the variable sumthisrow will keep only the last value just like:
sumthisrow = Reader.GetValue(Reader.FieldCount - 1).ToString();
EDIT: Also consider using a StringBuilder for creation of thisrow variable.
EDIT 2: Put your disposable objects into a using statement.
Related
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["DeathWish"].ToString();
con.Open();
string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text);
SqlCommand cmd = new SqlCommand(query,con);
SqlDataReader dr = cmd.ExecuteReader();
string[] s = new string[] { };
while (dr.Read())
{
s = dr["Decision"].ToString().Split(',');
}
int length = s.Length;
for (int i = 0; i < length - 1; i++)
{
string fetr = s[i];
for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
{
if (checkedListBox1.Items[j].ToString() == s[i])
{
checkedListBox1.SetItemChecked(j, true);
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}
string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text); is the line with error.
2nd picture edited* I wanted to retrieve a specific value on the database using checkedboxlist
this is the image:
error msg
i wanted to retrieve the data on the database and show the specific value
So a couple of things:
Consider enclosing your DB access code in a using block, and instantiating a new connection using your connection string. This ensures that - either by error or by completion of the block - the connection is correctly closed and disposed off.
Secondly, moving the try/catch inside of the using statement is good practice if you're also working with transactions, as you can commit on completion or rollback in your catch block.
Finally, never use string concatenation to build your queries, when the source of the data you're concatenating with comes from a user control (hell, just never do it). SQL injection is still the OWASP number 3 security risk in software to this day, and it needs to be squashed.
Mandatory reading:
OWASP - Top 10 Web Application Security Risks
SQL Injection - Wikipedia
SQL Injection - Technet
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
// a SqlConnection enclosed in a `using` statement will auto-close, and will ensure other resources are correctly disposed
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DeathWish"].ToString()))
{
try
{
con.Open()
string[] s = new string[] { };
string query = "Select [ID],Decision from Data where [ID]=#id order by Decision";
SqlCommand cmd = new SqlCommand(query, con);
SqlParameter idParam = new SqlParameter();
idParam.ParameterName = "#id";
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s = dr["Decision"].ToString().Split(',');
}
int length = s.Length;
for (int i = 0; i < length - 1; i++)
{
string fetr = s[i];
for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
{
if (checkedListBox1.Items[j].ToString() == s[i])
{
checkedListBox1.SetItemChecked(j, true);
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}
}
}
Your Connection is (still) open, so you have to check if it is closed. If it is you can open a new connection.
So try this:
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
if(con.State == ConnectionState.Closed)
{
con.Open();
}
con.ConnectionString = ConfigurationManager.ConnectionStrings["DeathWish"].ToString();
string query = string.Format("Select [ID],Decision from Data where [ID]='{0}' order by Decision", textBox1.Text);
SqlCommand cmd = new SqlCommand(query,con);
SqlDataReader dr = cmd.ExecuteReader();
string[] s = new string[] { };
while (dr.Read())
{
s = dr["Decision"].ToString().Split(',');
}
int length = s.Length;
for (int i = 0; i < length - 1; i++)
{
string fetr = s[i];
for (int j = 0; j <= checkedListBox1.Items.Count - 1; j++)
{
if (checkedListBox1.Items[j].ToString() == s[i])
{
checkedListBox1.SetItemChecked(j, true);
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + ex.ToString());
}
}
I want to show data from data table on form_load using list box, and later update that data from list box on button click by Insert command. Function for that is fill_List(). This is my code:
OleDbConnection konekcija;
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataTable dt = new DataTable();
public Form2()
{
InitializeComponent();
string putanja = Environment.CurrentDirectory;
string[] putanjaBaze = putanja.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", putanjaBaze[0]);
konekcija = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|\B31Autoplac.accdb");
}
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
fill_List();
}
private void btnUpisi_Click(object sender, EventArgs e)
{
string s1, s2, s3;
s1 = tbSifra.Text;
s2 = tbNaziv.Text;
s3 = tbOpis.Text;
string Upisi = "INSERT INTO GORIVO (GorivoID, Naziv, Opis) VALUES (#GorivoID, #Naziv, #Opis)";
OleDbCommand komUpisi = new OleDbCommand(Upisi, konekcija);
komUpisi.Parameters.AddWithValue("#GorivoID", s1);
komUpisi.Parameters.AddWithValue("#Naziv", s2);
komUpisi.Parameters.AddWithValue("#Opis", s3);
string Provera = "SELECT COUNT (*) FROM GORIVO WHERE GorivoID=#GorivoID";
OleDbCommand komProvera = new OleDbCommand(Provera, konekcija);
komProvera.Parameters.AddWithValue("#GorivoID", s1);
try
{
konekcija.Open();
int br = (int)komProvera.ExecuteScalar();
if(br==0)
{
komUpisi.ExecuteNonQuery();
MessageBox.Show("Podaci su uspesno upisani u tabelu i bazu.", "Obavestenje");
tbSifra.Text = tbNaziv.Text = tbOpis.Text = "";
}
else
{
MessageBox.Show("U bazi postoji podatak sa ID = " + tbSifra.Text + ".", "Obavestenje");
}
}
catch (Exception ex1)
{
MessageBox.Show("Greska prilikom upisa podataka. " + ex1.ToString(), "Obavestenje");
}
finally
{
konekcija.Close();
fill_List();
}
}
Instead of this
It shows me this (added duplicates with new data)
Is there a problem in my function or somewhere else?
Another bug caused by global variables.
You are keeping a global variable for the DataTable filled by the fill_list method. This datatable is never reset to empty when you call fill_list, so at every call you add another set of rows to the datatable and then transfer this data inside the listbox. Use a local variable.
But the same rule should be applied also to the OleDbConnection and OleDbCommand. There is no need to keep global instances of them. Creating an object is really fast and the convenience to avoid global variables is better than the little nuisance to create an instance of the connection or the command.
void fill_List()
{
using(OleDbConnection konekcija = new OleDbConnection(......))
using(OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija))
{
DataTable dt = new DataTable();
konekcija.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(komPrikaz);
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
}
}
Clear your DataTable before filling it again.
void fill_List()
{
konekcija.Open();
OleDbCommand komPrikaz = new OleDbCommand("SELECT * FROM GORIVO ORDER BY GorivoID ASC", konekcija);
adapter.SelectCommand = komPrikaz;
dt.Clear(); // clear here
adapter.Fill(dt);
listBox1.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
string pom;
pom = dt.Rows[i][0].ToString() + " " + dt.Rows[i][1].ToString() + " " + dt.Rows[i][2];
listBox1.Items.Add(pom);
}
konekcija.Close();
}
I'm trying to populate a generic collection but having problems. I'm trying to populate myBookings, which is supposed to store a List. The methods below should fill myBookings with the correct List but for some reason when I count the result (int c), I'm getting a return of 0. Can anyone see what I'm doing wrong?
// .cs
public partial class _Default : System.Web.UI.Page
{
iClean.Bookings myBookings = new iClean.Bookings();
iClean.Booking myBooking = new iClean.Booking();
iClean.Controller myController = new iClean.Controller();
ListItem li = new ListItem();
protected void Page_Load(object sender, EventArgs e)
{
CurrentFname.Text = Profile.FirstName;
CurrentUname.Text = Profile.UserName;
CurrentLname.Text = Profile.LastName;
myBookings.AllBookings = this.GetBookings();
int c = myBookings.AllBookings.Count();
Name.Text = c.ToString();
Address.Text = myBooking.Address;
Phone.Text = myBooking.Phone;
Date.Text = myBooking.DueDate.ToString();
Comments.Text = myBooking.Comments;
}
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
for (int i = 0; i < records.Count; i++)
{
iClean.Booking tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
public ArrayList Select(string table, string conditions)
{
// Create something to hosue the records.
ArrayList records = new ArrayList();
try
{
// Open a connection.
OleDbConnection myConnection = new OleDbConnection(this.getConnectionString());
myConnection.Open();
// Generate the SQL
string sql = "SELECT * FROM " + table;
if (conditions != "") { sql += " WHERE " + conditions; }
// Console.WriteLine("Select SQL: " + sql); // In case we need to debug
// Run the SQL
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
OleDbDataReader myReader = myCommand.ExecuteReader();
// Go through the rows that were returned ...
while (myReader.Read())
{
// ... create Hashtable to keep the columns in, ...
Hashtable row = new Hashtable();
// ... add the fields ...
for (int i = 0; i < myReader.FieldCount; i++)
{
row.Add(myReader.GetName(i), myReader[i]);
}
// ... and store the row.
records.Add(row);
}
// Make sure to close the connection
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return records;
}
public string getConnectionString()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IQQuotes.accdb;";
return connectionString;
}
}
Just a guess, but try this:
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
iClean.Booking tempBooking = new iClean.Booking();
for (int i = 0; i < records.Count; i++)
{
tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
I have array of timer.I want timer0 work with 1st dataValue in _dataValues, 2nd timer work with 2nd dataValue in _dataValues, 3rd timer work with 3rd dataValue in _dataValues and etc and also show result in label in windows form.I use System.Windows.Forms.Timer.Here is my code,
void PrepareTimers(List<int> _dataValues)
{
int i = 0;
foreach (int dataValue in _dataValues)
{
timerNames[i] ="timer"+ string.Format("{0}", i);
timer1[i] = new Timer();
t[i] = dataValue.ToString();
a[i] = timer1[i].ToString();
a[i] = t[i];
timer1[i].Tick += new EventHandler(timer_Tick);
timer1[i].Interval = (1000) * (1);
label = new Label();
label.Name = "label_name" + i;
label.Size = new Size(200, 20);
label.Location = new Point(45, 100 + i * 30);
label.TabIndex = i;
label.Visible = true;
this.Controls.Add(label);
dict[timer1[i]] = label;
timer1[i].Enabled = true;
timer1[i].Start();
i++;
}
}
private void timer_Tick =(object sender, EventArgs e)
{
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
i = 0;
string u = "UPDATED";
mycon.Open();
foreach (int dataValue in _dataValues)
{
if (a[i] == dataValue.ToString())
{
MySqlCommand cmd = new MySqlCommand("UPDATE sms_data_bankasia set flag = " + (dataValue.ToString()) + " *2 , sendingstatus = '" + u + "' WHERE flag = " + dataValue.ToString() + " LIMIT 1", mycon);
cmd.ExecuteNonQuery();
Console.WriteLine("row update" + dataValue.ToString());
mycon.Close();
mycon.Open();
string sql = "SELECT count(flag) FROM sms_data_bankasia where sendingstatus='UPDATED' AND flag = " + (dataValue.ToString()) + " *2 group by flag";
MySqlCommand comd = mycon.CreateCommand();
comd.CommandText = sql;
MySqlDataReader dtr = comd.ExecuteReader();
try
{
while (dtr.Read())
{
Timer t = (Timer)sender;
dict[t].Text = dtr[0].ToString() + " program Updated " + dataValue.ToString();
}
dtr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
i++;
}
mycon.Close();
}
But it update 4 row in per sec and every EventHandler work with every dataValue.I want 1st timer update 1 row in 1 sec and show in label that 1row update with 1st dataValue and 2nd timer update 1row in 1 sec and show in another label that 1 row update with 2nd dataValue and so on.What should i do? Any one can help me?
In PrepareTimers assign a tag to each timer: timer1[i] = new Timer(); timer1[i].Tag = i;
Then you can use this in timer_Tick instead of looping through the whole array:
i = (int)((Timer)sender).Tag;
int dataValue = _dataValues[i];
//...
instead of:
i = 0;
foreach (int dataValue in _dataValues)
{
if (a[i] == dataValue.ToString())
//...
in line
urls[i] = Reader.GetValue(i).ToString();
it say Error 1 The name 'i' does not exist in the current context
how can I fix it
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT url FROM `listweb` WHERE `url` IS NOT NULL AND ( `webbordkind` = '¿¿¿¿¿¿¿¿¿¿¿¿' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[2];
string thisrow = "";
string sumthisrow = "";
string urlname ;
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
thisrow += Reader.GetValue(i).ToString();
urlname = Reader.GetValue(i).ToString();
urls[i] = Reader.GetValue(i).ToString();
// System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = sumthisrow + thisrow;
You need to add braces to your for loop otherwise it only loops the first statement.
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
urlname = Reader.GetValue(i).ToString();
urls[i] = Reader.GetValue(i).ToString();
}
You are missing braces here:
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
urlname = Reader.GetValue(i).ToString();
urls[i] = Reader.GetValue(i).ToString();
}
I'd also advise you not to create strings by concatenating in a loop. Put them in a List<string> first then at the end convert it to an array (except in .NET 4.0 or newer where this step is not required) and use string.Join. As well as giving better performance this allows allows you to add a separator between the fields, which I assume you want...
If you don't need a separator then you can use a StringBuilder.
Your braces are missing for the FOR loop. The variable i is available only within the FOR loop which is only one line after your loop in your case.
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
urlname = Reader.GetValue(i).ToString();
urls[i] = Reader.GetValue(i).ToString();
}