Show information from MySQL database - c#

I want to pass the information I get from a database to a label. How can I pass the information into a variable.
How can I do this?
private void button1_Click(object sender, EventArgs e)
{
var numero = textBox1.Text;
string connection_string = "datasource=xxx;port=111;username=xxx;password=xxx";
string Query = "select * from xxx.lojass where nome =" + numero;
MySqlConnection conDate = new MySqlConnection(connection_string);
MySqlCommand cmdDate = new MySqlCommand(Query, conDate);
MySqlDataReader myReader;
try
{
conDate.Open();
myReader = cmdDate.ExecuteReader();
MessageBox.Show("Conected");
while (myReader.Read())
{
label1.Text
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Proper coding. Explanation in code comments below
private void button1_Click(object sender, EventArgs e)
{
try
{
const connStr = "datasource=xxx;port=111;username=xxx;password=xxx"; // constant
// Instead of "select *" select particular column(s), it will help with reader columns later
var sql = "select column1 from xxx.lojass where nome = #1"; // you need to parameterize. Never push text box value directly into sql
// important to use "using" to release resources
using (var conn = new MySqlConnection(connStr))
{
using (var cmd = new MySqlCommand(sql, conn))
{
// assuming "nome" is string. If the value is other datatype - convert it
// Better yet - create parameter where you explicitly specify mySql data type
cmd.Parameters.AddWithValue("#1", textBox1.Text);
conn.Open();
using (var reader = cmd.ExecuteReader()) // Since single value expected another way doing it - ExecuteScalar
{
// you only fill one single value, so makes sense to use IF, not WHILE
if (reader.Read())
label1.Text = reader["column1"].ToString();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

user selection Combobox then to Labels according to database MS Access c#

i have the following code below and what im trying to do is on the comboBox there is "ID" from my database and this ID represents every survey detail that Admin used to create so when the user goes to view the survey they click on the survey number in comboBox and the labels will change according to the database. I tried it with the below code but unfortunatley all it seems to do is grab a random one, if someone could help that would be amazing. It doesnt have to be like below, just as long as it works,
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You can try this to search data from database using Combobox
I use parameterized query to avoid SQL Injection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con.Open();
string query = "SELECT * FROM tbl_newsurvey WHERE [ColumnName] = #ComboBoxValue";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ComboBoxValue", comboBox1.SelectedIndex.ToString())
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
string name = reader["txtname"].ToString();
lblname.Text = name;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}

How do I assign values to checkboxes from an ArrayList

I hope you're well.
I want to get the data from my Access database and assign each row to a checkbox in a form in c#. So, I have read the data from the database to an arraylist. Now, I do not know how exactly I can assign those values to the checkboxes from the ArrayList.
I thought I could just say:
checkbox1.Text = Cakes(0);
but it is saying that I need a method.
Please assist me.
Here is the code that I have so far.
public partial class Customer : Form
{
private OleDbConnection connection = new OleDbConnection();
public Customer()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=FILE PATH;Persist Security Info=False;";
}
private void Customer_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * Cakes";
List<string> Cakes = new List<string>();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Cakes.Add(reader["Product Name"].ToString());
}
}
checkBox1.Text = Cakes(0);
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
In the while loop add all the values to the Cakes list, after that assign the list as the CheckBox text, based on the code example (notice the Cakes[0]), also put the connection in a using statement so it's disposed and closed (removed the connection.Close() and moved the reader):
private void Customer_Load(object sender, EventArgs e)
{
try
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * Cakes";
List<string> Cakes = new List<string>();
using (connection)
{
var reader = command.ExecuteReader();
while (reader.Read())
{
Cakes.Add(reader["Product Name"].ToString());
}
}
checkBox1.Text = Cakes[0];
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}

Cookies being automatically empty

I have cookies named empid which stores the id of employee i am going to use. But whenever i try to get the value of any cookie its value is set to null automatically and this code is from a partial class which is inherited by page . What if i want to create a class that contains all the database related code and want to use it in everypage
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ToString()))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
cn.Open();
SqlDataReader conReader;
conReader = null;
mycomment.Text = Response.Cookies["empid"].Value;
// cmd.CommandText = "Select * from comments where c_from = " + Response.Cookies["cid"] + " and c_to = "+ Response.Cookies["empid"].ToString();
cmd.Connection = cn;
mycomment.Text = cmd.CommandText;
cmd.CommandType = CommandType.Text;
conReader = cmd.ExecuteReader();
while (conReader.Read())
{
mycomment.Text += conReader[3].ToString();
}
}
catch (Exception ex)
{
Console.Write(ex);
}
finally
{
cn.Close();
}
}
}
}
You're getting Cookies from the Response object - which is the outgoing cookies set, not the Request object which is the set of cookies coming from the client.
Change it to mycomment.Text = this.Request.Cookies["empid"].Value.
I also see you're forming SQL commands by using String Concatenation without any sanitation. DO NOT EVER DO THIS. Instead use parameters:
cmd.CommandText = "SELECT * FROM comments WHERE c_from = #from AND c_to = #to";
cmd.Parameters.AddWithValue("#from", this.Request.Cookies["cid"].Value);
cmd.Parameters.AddWithValue("#to" , this.Request.Cookies["empid"].Value);

SQL datareader reading inconsistently

I have the following code in C#-
private void sendnotificationmail(string enqid)
{
try
{
connection.Open();
List<string> maillist = new List<string>();
string sql = "SELECT TrussLog.repmail, TrussLog.branchemail, TrussEnquiry.DesignerEmail FROM TrussLog FULL OUTER JOIN TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID where TrussEnquiry.Enquiry_ID = '" + enqid + "'";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (!string.IsNullOrEmpty(reader[0].ToString()))
{
maillist.Add(reader[0].ToString());
}
if (!string.IsNullOrEmpty(reader[1].ToString()))
{
maillist.Add(reader[1].ToString());
}
if (!string.IsNullOrEmpty(reader[2].ToString()))
{
maillist.Add(reader[2].ToString());
}
}
connection.Close();
if (result != DialogResult.Cancel)
{
processmail(maillist);
}
}
catch (Exception)
{
}
}
I am getting the value of the variable enqid from a combobox on my Windows form.The contents of the combobox are retrieved from the database. On form load, the combobox displays the first enquiryID retrieved from the database. When I run my program the data reader skips the loop. However if I select a different enquiry in the combobox, the data reader works properly
It seems that you've forgot to associate Command with the Connection:
// SendNotificationMail is more readable then sendnotificationmail
private void sendnotificationmail(string enqid) {
// put IDisposable into using...
using (SqlConnection con = new SqlConnection("ConnectionStringHere")) {
con.Open();
using (SqlCommand cmd = new SqlCommand()) {
cmd.Connection = con; // <- You've omitted this
// have SQL readable
cmd.CommandText =
#"SELECT TrussLog.repmail,
TrussLog.branchemail,
TrussEnquiry.DesignerEmail
FROM TrussLog FULL OUTER JOIN
TrussEnquiry ON TrussLog.enquirynum = TrussEnquiry.Enquiry_ID
WHERE TrussEnquiry.Enquiry_ID = #prm_Id";
// use parametrized queries
cmd.Parameters.AddWithValue("#prm_Id", enqid);
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
...
}
}
}
}
}
And never, never after write code alike
catch (Exception)
{
}
which means "just ignore all the errors and continue".

how to search table through textbox?

I have piece of query that search database from text box.
My question is how can insert search result column by column to separated text box, I mean each column go to one textbox.
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Try this :
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(#"Select Name, FileName From Table Where Name Like #Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
}
I assume that, your search will return only one row.
You can use datareader to achieve that. I modified your function with below code:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Note: Your code is vulnerable to sqlinjection. Learn things to avoid it.

Categories

Resources