OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\`Hp\Desktop\PROGRAM1\notificationSystem\notificationSystem\Database.accdb";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = cn;
//reg();
cn.Open();
cmd.CommandText = "select article from news where npublished = '" + metroDateTime1.Text + "' AND ntime = '" + label4.Text + "'";
//AND ntime = '" + label4.Text + "'
//Scalar executes the fetching of data
var a = cmd.ExecuteScalar();
//this statement gets the process of getting the data from the database to label
if (a != null)
{
label1.Text = "" + a.ToString();
//while in this statement is displaying the data inside the textbox
metroTextBox2.Text = label1.Text;
}
else if (metroTextBox2.Text != null)
{
//SEND SMS PROCESS
}
else if (metroTextBox2.Text == null)
{
//REPEAT FETCH
}
cn.Close();
So the code above works but I use a button, and I have to press the button everytime to fetch information. Does anyone have any advice on what should I do to automatically fetch information from database using datagridview and display it on textbox?
I want to put the code on form load, so everytime I will run the program it will automatically fetch and do its job. But I don't know how to do it and I tried but it won't work.
Any help is gradly appreciated.
Related
I am trying to display the values from database. The textbox values are displayed successfully but checkbox values are not displayed, and it shows the error. I get the error shown in this screenshot:
Error Message
My code:
sql = "select * from repair where repairid = '" + repairid + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dread;
con.Open();
dread = cmd.ExecuteReader();
while (dread.Read())
{
checkBox7.CheckState = dread[6].ToString();
}
if(dread[6].ToString = = "True")
{
CheckBox7.Checked = "true";
}
else
{
CheckBox7.Checked = "false";
}
I am literally stumped. I've spent two days working at this. I have tried scrolling through the internet but nothing I seem to try worked like try/catch blocks, using etc.
So here goes..
I have a Web Application asp c# , which is connected to an sql database that I have written within Visual Studio 'Database.mdf' .
The Database contains a number of Football Players and their details, I want to be able to update and delete these details however my sql commands are not coming into affect (I am new to this so it's probably something ridiculously simple to most of you but nonetheless)
I have a number of buttons in which I use to both sort the data on screen in order. They work fine, I just use a static variable string for that. However the methods I have written for the SQL Commands are not working for me. The methods are called also on Button_Click but in the case of Update/Delete nothing changes, it's as if the sql query never updated the database
Please if you have any idea how I can fix this let me know. My head's fried.
Here are a few of the methods including display data :
protected void Page_Load(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\David\\Desktop\\WebApplication5\\WebApplication5\\App_Data\\Database2.mdf\";Integrated Security=True";
cn = new SqlConnection(str);
cn.Open();
mycount();
displayData();
// updateData();
// deleteData();
}
protected void mycount()
{ // count no of els in table
max = 0;
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
while (reader.Read()) max++;
reader.Close();
}
protected void displayData()
{
var cmd = cn.CreateCommand();
cmd.CommandText = sqlQuery;
var reader = cmd.ExecuteReader();
for (int i = 0; i < count; i++) reader.Read();
TextBox1.Text = "" + reader[0];
TextBox2.Text = "" + reader[1];
TextBox5.Text = "" + reader[2];
TextBox6.Text = "" + reader[3];
TextBox7.Text = "" + reader[4];
TextBox8.Text = "" + reader[5];
reader.Close();
}
protected void updateData()
{
var cmd = cn.CreateCommand();
string query = "UPDATE [Footballer] SET [Appearances] = #appear , [NumberOfGoals] = #goals Where [PlayerName] = #name ";
cmd.CommandText = query;
int appear = int.Parse(TextBox6.Text);
int goals = int.Parse(TextBox8.Text);
string name = TextBox1.Text;
cmd.Parameters.AddWithValue("#Player_ID", name);
cmd.Parameters.AddWithValue("#app", appear);
cmd.Parameters.AddWithValue("#goals", goals);
cmd.ExecuteNonQuery();
}
protected void deleteData()
{
string searchName = TextBox4.Text;
TextBox1.Text = "Deleted";
TextBox2.Text = "Deleted";
TextBox5.Text = "Deleted";
TextBox6.Text = "Deleted";
TextBox7.Text = "Deleted";
TextBox8.Text = "Deleted";
var cmd = cn.CreateCommand();
string query = "Delete from [Footballer] where [PlayerName] = #PlayerName_ID";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#PlayerName_ID", searchName);
cmd.ExecuteNonQuery();
}
Here is a screen of what I got visually if it helps:
Gui View
Most probably because you do not commit the transaction. There is an example here https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqltransaction.commit
There was a problem. I checked the connection to the database - everything works.
But when I try to check the lines in the database, then the error pops up:
System.InvalidOperationException: "Connection must be valid and open." c#
How can i fix this?
private void button1_Click(object sender, EventArgs e)
{
try
{
MySqlConnection conn = GetDBConnection();
conn.Open();
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM 'rcc_base' WHERE login='" + this.textBox1.Text + "', pass='" + this.textBox2.Text + "' ;");
MySqlDataReader myReader;
MessageBox.Show("Connection...");
myReader = selectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("All nice");
}
else
{
MessageBox.Show("Login failed");
}
conn.Close();
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
In your MySqlCommand you are not using your MySqlConnection :( .So change it as follows
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM rcc_base WHERE 'login' ='" + this.textBox1.Text + "' AND 'pass' ='" + this.textBox2.Text + "' ;",conn);
Also , create a new instance of the MySqlConnection like :
MySqlConnection conn = new MySqlConnection;
conn = GetDBConnection();
And a few suggestions:Your code is not good.Don't give direct values to columns in the SqlCommand rahter pass parameters like #abc , this will also prevent sql-injections.Sample :
MySqlCommand selectCommand = new MySqlCommand("SELECT COUNT(*) FROM rcc_base WHERE login=#username AND pass=#password;",conn);
selectCommand.Parameters.Add("#username",MySqlDbType.VarChar).Value = textBox1.Text;
selectCommand.Parameters.Add("#password",MySqlDbType.VarChar).Value = textBox2.Text;
///Now to check if data exists in the database or not
int count = Convert.ToInt32(selectCommand.ExecuteScalar());
if(count > 0)
{
///data exists-login successful
}
else
{
///data doesn't exists , login failed
}
Also you should open the connection on form load so that you can access the database throughout the class/form.It is a better way to do it :)
i passed a value from form1 to form2 and used that value as a where condition however i cant seem to fix it. I'm updating a table btw. any help would be greatly appreciated.
SqlConnection cn = new SqlConnection("Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=inventory2;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adptr = new SqlDataAdapter();
DataSet dt = new DataSet();
private void button1_Click(object sender, EventArgs e)
{
if (this.Text == "EDIT")
{
cmd.CommandText = string.Format("Update Items Set (Barcode='" + txtcode.Text + "' ,Productname= '" + txtitemname.Text + "',Prices= '" + txtPrices.Text + "' ,Quantity= '" + txtquantity.Text + "' ,Brand= '" + txtbrand.Text + "',Expiry= '" + txtexpiry.Text + "',Description='" + txtdescription.Text + "' ,Critical= '" + txtcritical.Text + "' where Barcode = '" + txtTry.Text + "')", cn);
cmd.ExecuteNonQuery();
MessageBox.Show("Records Updated!");
txtcode.Text = "";
txtitemname.Text = "";
txtPrices.Text = "";
txtquantity.Text = "";
txtbrand.Text = "";
txtexpiry.Text = "";
txtdescription.Text = "";
txtcritical.Text = "";
}
else
{
MessageBox.Show("Invalid");
}
I think the error message is clear enough, you have to assign the connection to the command which is going to be executed. But here you may face another big issue, ie., the SqlInjection because of this concatenated query text query, You have to use parameterization instead to avoid the injection, in short your code would be looks like the following:
string connectioStr = "Data Source=DESKTOP-MQKIBSK\\SQLEXPRESS;Initial Catalog=inventory2;Integrated Security=True";
string querySQL = "Update Items Set Barcode=#Barcode,Productname=#Productname,Prices=#Prices,Quantity=#Quantity where Barcode = #condition";
// add more columns as you needed in the set
using (SqlConnection conSQL = new SqlConnection(connectioStr))
{
using (SqlCommand cmdSQL = new SqlCommand())
{
cmdSQL.Connection = conSQL;
cmdSQL.CommandText = querySQL;
cmdSQL.Parameters.Add("#Barcode", SqlDbType.VarChar).Value = txtcode.Text;
cmdSQL.Parameters.Add("#Productname", SqlDbType.VarChar).Value = txtitemname.Text;
cmdSQL.Parameters.Add("#Prices", SqlDbType.VarChar).Value = txtPrices.Text;
cmdSQL.Parameters.Add("#Quantity", SqlDbType.VarChar).Value = txtquantity.Text;
cmdSQL.Parameters.Add("#condition", SqlDbType.VarChar).Value = txtcode.Text;
// Add all parameters specified in the query
// use appropriate datatypes as per the type of columns
}
}
You can specify the connection and query of the command at the time of initializing the command; in this case the command initialization would be like this:
SqlCommand cmdSQL = new SqlCommand(querySQL,conSQL);
i am coding for a commenting system in asp.net C# but i am stopped at delete command because of i am not using any type of serial numbers to comments posted, then how can i able to delete a specific comment, i am just using a username, date, time, and text in comment. Can anyone help me please that how to use a delete command in this condition??
here is my code for posting:
protected void pospost_Click(object sender, EventArgs e)
{
string login;
if (HttpContext.Current.Session["UserName"] != null)
{
login = HttpContext.Current.Session["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from mobiles_pos";
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
DataRow rw = ds.Tables[0].NewRow();
rw[0] = Model.Text.ToString();
rw[1] = titlepos.Text.ToString();
rw[2] = txtpos.Text.ToString();
rw[3] = DateTime.Today.Date.ToString();
rw[4] = DateTime.Now.TimeOfDay.ToString();
rw[5] = login.ToString();
ds.Tables[0].Rows.Add(rw);
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = con;
cmd1.CommandText = "insert into mobiles_pos values('" + Model.Text + "','" + titlepos.Text + "','" + txtpos.Text + "','" + DateTime.Today.Date + "','" + DateTime.Now.TimeOfDay + "','" + login + "')";
da.InsertCommand = cmd1;
da.Update(ds);
con.Close();
titlepos.Text = "";
txtpos.Text = "";
//DataList2.DataSource = ds;
//DataList2.DataBind();
BindDataList2();
}
}
Best - Add a Primary key to the "mobiles_pos" table since your using sql just use an identity field it will auto increment for you.
or
Quick - Use a combination of the User name and date comment was intered you must use the full date time or it will delete everything that user entered that day.
"Delete from mobiles_pos where username = #UserName and createdDate = #createdDate"