Yahoo weather Forecast c# - c#

Looking for Getting current weather and weather forecast for London
woeid 44418
https://query.yahooapis.com/v1/public/yql? q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20woeid%20%3D044418)&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys
How to get forecast for this ?
Following is code for weather today .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using MySql.Data.MySqlClient;
using System.Windows.Forms.DataVisualization.Charting;
using System.Runtime.InteropServices;
namespace weatherstation1
{
public partial class Form2 : Form
{
string Town;
string Temperature;
string Temperature2;
string Condition;
string Humidity;
string Windspeed;
string ConditionCode;
int cityNumber = 44418;
public Form2()
{
InitializeComponent();
Getweather();
GetCondition();
textBox1.Text = Town;
textBox3.Text = Condition;
textBox4.Text = Humidity;
textBox5.Text = Windspeed;
}
private void toolStripLabel1_Click(object sender, EventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout = new AboutBox1();
frmAbout.Show();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
}
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout = new AboutBox1();
frmAbout.Show();
}
private void Getweather()
{
string query = String.Format("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20woeid%20%3D044418)&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
XmlDocument wData = new XmlDocument();
wData.Load(query);
XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
XmlNodeList nodes = wData.SelectNodes("/rss/channel/item/yweather:forecast", manager);
Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value;
Temperature2 = ((Double.Parse(Temperature) - 32) / 1.8).ToString();
Condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["text"].Value;
ConditionCode = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["code"].Value;
Time = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["date"].Value;
// Windspeed = channel.SelectSingleNode("yweather:wind", manager).Attributes["speed"].Value;
// Town = channel.SelectSingleNode("yweather:location", manager).Attributes["city"].Value;
}
private void database()
{
// string Time = DateTime.Now.ToString("d/M/yyyy HH:mm");
string MyConnection = "datasource=localhost;database=weatherstation;port=3306;username=weatherstation;password=123456";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
string query1 = "INSERT INTO weatherstation1.London"+
"(City, Time, Temperature, Temperature2, WeatherCondition) VALUES('" + Town +
"','" + Time + "','" + Temperature + "','" + Temperature2 + "' + Condition + "');";
MySqlCommand MyCommand = new MySqlCommand(query1, MyConn);
MySqlDataReader MyReader;
MyConn.Open();
MyReader = MyCommand.ExecuteReader();
}
public void GetCondition()
{
string cc = ConditionCode;
if (cc <= 'Showers')
{
weatherCondition.ImageLocation = "showers.png";
}
else if (cc <= 'Scattered Showers')
{
weatherCondition.ImageLocation = "scatteredshowers.png";
}
else if (cc <= 'Mostly Cloudy')
{
weatherCondition.ImageLocation = "mostlycloudy.png";
}
else if (cc <= 'Rain')
{
weatherCondition.ImageLocation = "rain.png";
}
else if (cc <= 'Mostly Cloudy')
{
weatherCondition.ImageLocation = "mostlycloudy.png";
}
else if (cc <= 'Rain')
{
weatherCondition.ImageLocation = "rain.png";
}
else if (cc >= 'Scattered Thunderstorms')
{
weatherCondition.ImageLocation = "scatteredthunderstorms.png";
}
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
Getweather();
textBox1.Text = Town;
textBox3.Text = Condition;
//textBox4.Text = Humidity;
//textBox5.Text = Windspeed;
}
private void button2_Click(object sender, EventArgs e)
{
database();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
}
private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
{
database();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void graph()
{
if (radioButton2.Checked)
{
MySqlDataReader MyReader2;
string MyConnection = "datasource=localhost;database=weatherstation;port=3306;username=weatherstation;password=123456";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection);
MyConn2.Open();
string query2 = " SELECT * FROM London ";
MySqlCommand MyCommand2 = new MySqlCommand(query2, MyConn2);
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
chart1.Series["Series1"].Points.AddXY(MyReader2.GetString("Time"), MyReader2.GetString("Temperature"));
chart1.Series["Series1"].ChartType = SeriesChartType.FastLine;
chart1.Series["Series1"].Color = Color.Blue;
}
}
if (radioButton1.Checked)
{
MySqlDataReader MyReader2;
string MyConnection = "datasource=localhost;database=weatherstation;port=3306;username=weatherstation;password=123456";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection);
MyConn2.Open();
string query2 = " SELECT * FROM London ";
MySqlCommand MyCommand2 = new MySqlCommand(query2, MyConn2);
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
chart1.Series["Series1"].Points.AddXY(MyReader2.GetString("Time"), MyReader2.GetString("Temperature2"));
chart1.Series["Series1"].ChartType = SeriesChartType.FastLine;
chart1.Series["Series1"].Color = Color.Blue;
}
}
}
private void button3_Click(object sender, EventArgs e)
{
graph();
Getweather();
database();
}
private void timer1_Tick(object sender, EventArgs e)
{
graph();
Getweather();
database();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
double celc = (Int32.Parse(Temperature) - 32) / (1.8);
string Temperature2 = celc.ToString();
textBox2.Text = Temperature2;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox2.Text = Temperature;
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
cityNumber = Int32.Parse(textBox7.Text);
timer1.Interval = Int32.Parse(textBox8.Text);
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void tabPage3_Click(object sender, EventArgs e)
{
}
private void toolStripTextBox1_Click(object sender, EventArgs e)
{
Getweather();
toolStripTextBox1.Text = "Temperature:" + Temperature + " F";
}
private void weatherCondition_Click(object sender, EventArgs e)
{
}
}
}
For database in localhost
CREATE TABLE London
(ID INT NOT NULL AUTO_INCREMENT, City VARCHAR(30) NOT NULL, Time VARCHAR(20) NOT NULL, Temperature VARCHAR(5) NOT NULL, Temperature2 VARCHAR(5) NOT NULL, WeatherCondition VARCHAR(30) NOT NULL, PRIMARY KEY (ID));

Can only say for Yahoo Weather JSON format. The result will be in query.results.channel.item.forecast. Check out the following example, which uses Newtonsoft.Json for JSON parsing:
dynamic jsonData = JObject.Parse(responseFromServer);
if (jsonData["query"].count == 0)
{
throw new Exception("Failed to obtain forecast from the server.");
}
var convertFromFtoC = jsonData["query"].results.channel.units.temperature == "F";
foreach (var v in jsonData["query"].results.channel.item.forecast)
{
var date = (DateTime)v.date;
var tempLo = (int)v.low;
var tempHi = (int)v.high;
if (convertFromFtoC)
{
tempLo = TemperatureConverter.FahrenheitToCelcius(tempLo);
tempHi = TemperatureConverter.FahrenheitToCelcius(tempHi);
}
dailyForecst.Add(new ForecastDataForTheDay { Date = date, TempLo = tempLo, TempHi = tempHi });
}

Related

When I try to load image from mysql database i get error "Parameter is not valid" and when i try to load an image from db

The program is made in C# and database is MySQL.
I have 2 errors, first one when program loads (parameter is not valid) and second one (You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(Slika) values (_binary '?PNG).
So i tried the #blob thing (before i was only saving it as pictureBox which people said its false) and i get this error.
Also good to mention that i always get saved the same file which is BLOB - 55B.
This is the code:
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
I get parameter is invalid in this code where image has to load from database as soon as program is started:
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And here is the whole code of the Form2 (Form1 works perfectly fine):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
public Form2()
{
InitializeComponent();
}
public byte[] save(PictureBox pb)
{
MemoryStream mstr = new MemoryStream();
pictureBox3.Image.Save(mstr, pb.Image.RawFormat);
return mstr.GetBuffer();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
string query = "select * from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
con.OpenConnection2();
string query2 = "update tabla set (Slika) values (#Blob)";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Blob", save(pictureBox3));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
pictureBox2.Image = pictureBox3.Image;
this.Refresh();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Thanks for any help!!
UPDATE
So I have decided to insert full data and image directly to table in phpmyadmin and when I entered credentials no errors were showing.
It just seems to be an error while converting to blob while updating the table, now if someone can help me with this i'm pretty new to C# and MySQL especially.
[1]: https://i.stack.imgur.com/KUK7a.png
UPDATE #2
I have changed mstr.GetBuffer() to mstr.GetArray(), also I added few lines to code and there are no more errors at saving picture, but I still have problem when it gets saved its corrupted or it just doesn't convert correctly.
When image gets uploaded it doesn't take nearly as much memory as same image i inserted directly into the table which had no problem loading into program.
So now it's just problem converting to binary ! guess, any help is appreciated!
This is how code looks after I added couple lines to save button:
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika = '" + ImageData + "' where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.AddWithValue("Slika", ImageData);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Refresh();
con.CloseConnection2();
}
I am happy to say that the problem has been fixed, it was indeed problem with saving picture to the database.
The problem was that I had to add parameter MySqlDbType.Blob like so:
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
And then I had to give that parameter the picture, like so:
cmd.Parameters["#Slika"].Value = ImageData;
Easy as that, feels much more rewarding when you solve the problem yourself :D
I will post the whole code so if someone wants to use it feel free.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace Maturski_Rad_1
{
public partial class Form2 : Form
{
Connectioncl con = new Connectioncl();
MySqlCommand cmd = new MySqlCommand();
string ID = Form1.id;
string fname;
public Form2()
{
InitializeComponent();
}
public Image displayImage(byte[] slika)
{
MemoryStream mstr = new MemoryStream(slika);
return Image.FromStream(mstr);
}
private void Form2_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = Form1.id; //just to check if its the correct ID
con.OpenConnection();
label1.Text = Form1.ime;
label2.Text = Form1.prezime;
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try {
string query = "select Slika,ID from tabla where ID='" + ID + "'";
cmd.Connection = Connectioncl.connection;
cmd.CommandText = query;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pictureBox2.Image = displayImage((byte[])dr["Slika"]);
}
dr.Close();
con.CloseConnection();
}
catch
{
MessageBox.Show("Error: Profilna slika nije pronadjena!");
}
}
private void toolTip1_Popup(object sender, PopupEventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void panel1_MouseHover(object sender, EventArgs e)
{
toolTip1.Show("Vas ID je: " + Form1.id, panel1);
toolTip1.UseFading = true;
}
private void label3_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToShortTimeString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Odaberite sliku";
dialog.Filter = " (*.jpg;*.png;*.jpeg) | *.jpg;*.png;*.jpeg";
DialogResult dr = new DialogResult();
dr = dialog.ShowDialog();
if (dr == DialogResult.OK)
{
pictureBox3.Image = new Bitmap(dialog.FileName);
fname = dialog.FileName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{
byte[] ImageData;
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
con.OpenConnection2();
string query2 = "update tabla set Slika= #Slika where ID = '" + ID + "'";
cmd.Connection = Connectioncl.connection2;
cmd.CommandText = query2;
cmd.Parameters.Add("#Slika", MySqlDbType.Blob);
cmd.Parameters["#Slika"].Value = ImageData;
cmd.ExecuteNonQuery();
MessageBox.Show("Data Save in Database ", "Data Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.CloseConnection2();
pictureBox2.Image = pictureBox3.Image;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox3.Image = pictureBox2.Image;
if (panel3.Visible = !panel3.Visible)
{
panel3.Visible = panel3.Visible;
}
else if(panel3.Visible = panel3.Visible)
{
panel3.Visible = !panel3.Visible;
}
}
}
}
Enjoy!
PS. Slika or #Slika means image in my language, its just that I called my image column in the database like that.

Windows Form App (.NET Framework) CRUD Project, changes successfully saves into DataGridView, but not the actual Database Table

This is my first time using C# and SQL. I've managed to get the datagridview to work, be it insert, update or delete. However, all the changes that is reflected in the datagridview is NOT updating in the SQL Table (When I open the database and click "Show Table Data", the Insert, Update and Delete changes are not reflected there.)
Please Help! All the videos I've searched up only shows their datagridview changes being reflected, but doesn't show if their SQL Table is actually updated.
My Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
namespace CRUDProj
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displaydata();
button3.Visible = false;
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
chk.HeaderText = "Select";
chk.ValueType = typeof(bool);
chk.Name = "chkbox";
infoDataGridView.Columns.Insert(0, chk);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'cRUDDBDataSet.Info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.cRUDDBDataSet.Info);
}
private void infoBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.infoBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.cRUDDBDataSet);
}
private void displaydata()
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Info]";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
DataTable dt = new DataTable();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
sdr.Fill(dt);
infoDataGridView.DataSource = dt;
sqlconn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "insert into [dbo].[Info] values (#Id, #FullName, #NRIC, #Phone, #Temperature, #LocationLevel, #Date)";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id", iDTextBox.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
MessageBox.Show("Record Successfully Inserted");
displaydata();
sqlconn.Close();
}
public string message = string.Empty;
private void button2_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in infoDataGridView.Rows)
{
bool issellected = Convert.ToBoolean(row.Cells["chkbox"].Value);
if (issellected)
{
message = Environment.NewLine;
message = row.Cells[1].Value.ToString();
}
}
label1.Text = message;
label1.Visible = true;
button3.Visible = true;
button1.Enabled = false;
button2.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "update [dbo].[Info] set Id=#Id, FullName=#FullName, NRIC=#NRIC, Phone=#Phone, Temperature=#Temperature, LocationLevel=#LocationLevel, Date=#Date where Id=#Id";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id" ,label1.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
infoTableAdapter.Update(cRUDDBDataSet.Info);
sqlconn.Close();
MessageBox.Show("Record Updated Successfully! ");
displaydata();
button3.Visible = false;
button1.Enabled = true;
button2.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
DataRowView drv = infoDataGridView.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { drv.Row };
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM dbo.Info", sqlconn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);
this.infoTableAdapter.Update(this.cRUDDBDataSet.Info);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
List<String> empselect = new List<String>();
DataGridViewRow row = new DataGridViewRow();
for (int i = 0; i<= infoDataGridView.Rows.Count-1; i++)
{
row = infoDataGridView.Rows[i];
if (Convert.ToBoolean(row.Cells [0].Value)==true)
{
string id = row.Cells[1].Value.ToString();
empselect.Add(id);
}
sqlconn.Open();
foreach (string s in empselect)
{
SqlCommand sqlcomm = new SqlCommand("delete from [dbo].[Info] where Id = ' " + s + " ' ", sqlconn);
sqlcomm.ExecuteNonQuery();
}
sqlconn.Close();
}
MessageBox.Show("Record Deleted Successfully! ");
displaydata();
}
private void iDTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
iDTextBox.Clear();
fullNameTextBox.Clear();
nRICTextBox.Clear();
phoneTextBox.Clear();
temperatureTextBox.Clear();
locationLevelTextBox.Clear();
dateTextBox.Clear();
}
}
}
Bind your DGV to Database this will help you to perform crud operations easily.
This is a sample code on DGV to perform some actions may it will help you. but make sure that you bind your DGV to the database table.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
string _name = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string _lname = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
string _sex = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
string _age = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
if (e.ColumnIndex == dataGridView1.Columns["delete"].Index && e.RowIndex >= 0)
{
if(groupBox1.Visible==true)
{
groupBox1.Visible = false;
}
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
DialogResult result = MessageBox.Show("Do You Want to delete?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result.Equals(DialogResult.OK) && service.deleterecord(_id, _name, _lname, _age, _sex))
{
MessageBox.Show("deleted record");
this.Close();
}
else
{
MessageBox.Show("not deleted");
}
}
if (e.ColumnIndex == dataGridView1.Columns["edit"].Index && e.RowIndex >= 0)
{
groupBox1.Visible = true;
firstname.Text = _name;
lastname.Text = _lname;
gender.Text = _sex;
age.Text = _age;
}
}
private void update_Click(object sender, EventArgs e)
{
string _fname = firstname.Text;
string _lname = lastname.Text;
string _age = age.Text;
string _sex = gender.Text;
try
{
if (string.IsNullOrWhiteSpace(_fname) || string.IsNullOrWhiteSpace(_lname) || string.IsNullOrWhiteSpace(_age) || string.IsNullOrWhiteSpace(_sex) || gender.Equals(null))
{
MessageBox.Show("Please enter the empty fields");
}
else
{
if (Updatedata("Update Query"))
{
MessageBox.Show("Record Updated");
//this.recordTableAdapter.Fill(this.task2DataSet.record);
groupBox1.Visible = false;
this.Size = new Size(595, 258);
this.Close();
}
else
{
MessageBox.Show("Failed to update");
}
}
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
}

No value given for one or more required parameters in Visual Studio

I'm having trouble when working with database in C#.
The problem is No value given for one or more required parameters whenever I click any buttons INSERT, DELETE, SEARCH,...
I check the field name and everything looks good. I have no idea what's wrong.
I include part of my source code below. Hopefully someone could guide me through this. Thank you!
namespace AccessDataForm
{
public partial class TourForm : Form
{
public TourForm()
{
InitializeComponent();
}
private void exitBtn_Click(object sender, EventArgs e)
{
Close();
}
private void tourForm_Load(object sender, EventArgs e)
{
}
private void viewButton_Click(object sender, EventArgs e)
{
disp_data();
}
public void disp_data()
{
string strSql = "Select * from Tour";
sql_exec(strSql);
}
private void insertBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(tourIDTbx.Text))
{
messageLbl2.Visible = true;
messageLbl2.Text = "Tour ID will be assigned by the Access DBMS";
}
else
{
if (string.IsNullOrWhiteSpace(tripLengthTbx.Text) ||
string.IsNullOrWhiteSpace(destinationTbx.Text) ||
string.IsNullOrWhiteSpace(detailTbx.Text) ||
string.IsNullOrWhiteSpace(priceTbx.Text))
{
messageLbl2.Text = "Warning: Some fields are missing data";
}
else
{
string strSql = "Insert INTO Tour ([TripLengthInDays], [Destination], [Detail], [PricePerPerson]) VALUES (";
strSql += "'" + tripLengthTbx.Text + "', '" + destinationTbx.Text;
strSql += "', '" + detailTbx.Text + "', '" + priceTbx.Text + "');";
sql_exec(strSql);
clearTextBox();
MessageBox.Show("Record inserted!!");
messageLbl2.Visible = false;
}
}
}
private void deleteBtn_MouseHover(object sender, EventArgs e)
{
tourID_check();
}
private void deleteBtn_MouseLeave(object sender, EventArgs e)
{
messageLbl2.Visible = false;
messageLbl2.Text = "";
}
private void deleteBtn_Click(object sender, EventArgs e)
{
string strSql = "DELETE FROM Tour WHERE [Tour ID] = ";
strSql += tourIDTbx.Text;
sql_exec(strSql);
messageLbl2.Text = "";
//MessageBox.Show("Record deleted!");
}
private void searchBtn_MouseHover(object sender, EventArgs e)
{
tourID_check();
}
private void searchBtn_MouseLeave(object sender, EventArgs e)
{
messageLbl2.Visible = false;
messageLbl2.Text = "";
}
private void searchBtn_Click(object sender, EventArgs e)
{
string strSql = "Select * from Tour where [Tour ID] = ";
strSql += tourIDTbx.Text;
sql_exec(strSql);
messageLbl2.Text = "";
}
private void editBtn_Click(object sender, EventArgs e)
{
string strSql = "UPDATE Tour SET ";
if (!string.IsNullOrWhiteSpace(tripLengthTbx.Text))
strSql += "[TripLengthInDays] = '" + tripLengthTbx.Text + "', ";
if (!string.IsNullOrWhiteSpace(destinationTbx.Text))
strSql += "[Destination] = '" + destinationTbx.Text + "', ";
if (!string.IsNullOrWhiteSpace(detailTbx.Text))
strSql += "[Detail] = '" + detailTbx.Text + "', ";
if (!string.IsNullOrWhiteSpace(priceTbx.Text))
strSql += "[PricePerPerson] = '" + priceTbx.Text + "' ";
strSql += "WHERE[Tour ID] = ";
strSql += tourIDTbx.Text;
sql_exec(strSql);
clearTextBox();
//MessageBox.Show("Record edited!!");
}
private void editBtn_MouseHover(object sender, EventArgs e)
{
messageLbl2.Visible = true;
messageLbl2.Text = "Please enter all fields for the operation";
}
private void editBtn_MouseLeave(object sender, EventArgs e)
{
messageLbl2.Visible = false;
messageLbl2.Text = "";
}
public void clearTextBox()
{
tourIDTbx.Text = "";
tripLengthTbx.Text = "";
destinationTbx.Text = "";
detailTbx.Text = "";
priceTbx.Text = "";
}
public void tourID_check()
{
if (string.IsNullOrWhiteSpace(tourIDTbx.Text))
{
messageLbl2.Visible = true;
messageLbl2.Text = "Please enter Tour's ID for the operation";
}
else
messageLbl2.Text = "";
}
public void sql_exec(string strSql)
{
//using (OleDbConnection con1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;data source=\Users\selin2\Documents\Visual Studio 2015\Projects\AccessDataForm\ExploringTravelAgent.accdb"))
using (OleDbConnection con1 = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=ExploringTravelAgent.accdb"))
{
try
{
OleDbCommand cmd = new OleDbCommand(strSql, con1);
con1.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable agent = new DataTable();
da.Fill(agent);
dataGridView1.DataSource = agent;
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con1.Close();
}
}
}
}
}
And here is how my Table looks like:
SQL table

How can I add search button code where I just want to find record and want to display it in listBoxes

I am new to C# and I am making a simple database project in which I want to add a functionality in which if user enter the identity number and click the button all the records will be displayed in the list boxes... Please help me to complete it... the code I want to add is in the last section of the code in button2_click.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace main_form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=windowDb;Integrated Security=True;Pooling=False");
SqlCommand command = new SqlCommand();
//SqlDataReader dataSearch;
private void Form1_Load(object sender, EventArgs e) {}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e) {}
private void btn_save_Click(object sender, EventArgs e)
{
if(id_Txt.Text!=""& f_txt.Text!=""& Lname_txt.Text!=""& m_txt.Text!=""& dateTimePicker1.Text!=""){
command.Connection = con;
con.Open();
command.CommandText = "insert into people(id,fname,lname,mobile,TDATE) values('"+id_Txt.Text+"','"+f_txt.Text+"','"+Lname_txt.Text+"','"+m_txt.Text+"','"+dateTimePicker1.Text/*Value.ToString()*/+"')";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Saved Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void search() {
listBox1.Items.Clear();
listBox2.Items.Clear();
listBox3.Items.Clear();
listBox4.Items.Clear();
listBox5.Items.Clear();
con.Open();
command.CommandText = "select * from people";
command.Connection = con;
SqlDataReader dataSearch = command.ExecuteReader();
if(dataSearch.HasRows){
while (dataSearch.Read())
{
listBox1.Items.Add(dataSearch["id"].ToString());
listBox2.Items.Add(dataSearch["fname"].ToString());
listBox3.Items.Add(dataSearch["lname"].ToString());
listBox4.Items.Add(dataSearch["mobile"].ToString());
listBox5.Items.Add(dataSearch["TDATE"].ToString());
}
}
con.Close();
}
private void btn_view_Click(object sender, EventArgs e)
{
search();
}
private void bn_update_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "" & f_txt.Text != "" & Lname_txt.Text != "" & m_txt.Text != "" & dateTimePicker1.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "update people set fname='" + f_txt.Text + "',lname='" + Lname_txt.Text + "',mobile='" + m_txt.Text + "',TDATE='" + dateTimePicker1.Text + "' where id='" +id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data updated Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox list = sender as ListBox;
if(list.SelectedIndex!=-1)
{
listBox1.SelectedIndex = list.SelectedIndex;
listBox2.SelectedIndex = list.SelectedIndex;
listBox3.SelectedIndex = list.SelectedIndex;
listBox4.SelectedIndex = list.SelectedIndex;
listBox5.SelectedIndex = list.SelectedIndex;
// retrive to TextBox of AllowDrop events;
/* id_Txt.Text = listBox1.SelectedIndex.ToString();
f_txt.Text = listBox2.SelectedIndex.ToString();
Lname_txt.Text = listBox3.SelectedIndex.ToString();
m_txt.Text = listBox4.SelectedIndex.ToString();
dateTimePicker1.Value = DateTime.Now;*/
id_Txt.Text = listBox1.SelectedItem.ToString();
f_txt.Text = listBox2.SelectedItem.ToString();
Lname_txt.Text = listBox3.SelectedItem.ToString();
m_txt.Text = listBox4.SelectedItem.ToString();
dateTimePicker1.Value = DateTime.Now;
}
}
private void btn_delete_Click(object sender, EventArgs e)
{
if (id_Txt.Text != "")
{
command.Connection = con;
con.Open();
command.CommandText = "delete from people where id='" + id_Txt.Text + "'";
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data deleted Successfully");
id_Txt.Clear();
f_txt.Clear();
Lname_txt.Clear();
m_txt.Clear();
dateTimePicker1.Value = DateTime.Now;
search();
}
}
private void label1_Click(object sender, EventArgs e) {}
private void button1_Click(object sender, EventArgs e) {}
private void button2_Click(object sender, EventArgs e)
{
if (text_search.Text == "")
{
MessageBox.Show("Enter the Rollno.");
}
else {
}
}
}
}

Automatic insertion of ID in execution

I have created inserting Employee details in Visual studio 2010.When I click on Add,it displays as added and the id automatically increments in backend.But instead of added,if I had to display as ("You EMP ID is somenumber(eg.10) )in front end while execution,what should I do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HRMSController;
using HRMSBusinessEntities;
using System.Data;
namespace HumanResourceManagementSystems
{
public partial class HRMSEmployee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = (string)(Session["LoginUser"]);
if (Session["LoginUser"] != null)
{
lblDisplay.Text = "Welcome..." + username;
}
Calendar1.Visible = false;
Label1.Visible = false;
txtcurrdate.Text = System.DateTime.Now.ToLongDateString();
}
protected void Btnmodified_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Added" ;
Clear();
}
public void Clear()
{
txtname.Text = "";
txtcurrdate.Text = "";
txtmodifieddate.Text = "";
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
txtmodifieddate.Text = Calendar1.SelectedDate.ToString();
}
protected void Button3_Click(object sender, EventArgs e)
{
Clear();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.Visible = true;
}
}
}
After adding the record you can pull up the max id record and show the record in the UI
Query might look like
Select * from Employee ORDER BY EmpId DESC LIMIT 1;
As suggested for performance issue we can do
Select max(EmpId) from Employee;
EDIT
add.Add(record);
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
Label1.Visible = true;
Label1.Text = Your Empl ID is " + LastID[0].ToString() ;
Clear();
con.Close();
Another way could be
protected void Add_Click(object sender, EventArgs e)
{
EmployeeEntity record = new EmployeeEntity
{
name = txtname.Text,
currentdate = Convert.ToDateTime(txtcurrdate.Text),
modifieddate = Convert.ToDateTime(txtmodifieddate.Text)
};
EmployeeController add = new EmployeeController();
add.Add(record);
Label1.Visible = true;
Label1.Text = "Your Empl ID is " + FetchLastID();
Clear();
}
public string FetchLastID()
{
SqlConnection con = new SqlConnection(ConnString);
con.Open();
IDbCommand Cmd = con.CreateCommand();
Cmd.CommandText = "Select max(EmpId) from Employee";
IDataReader LastID = Cmd.ExecuteReader();
LastID.Read();
return LastID[0].ToString() ;
}

Categories

Resources