Using if statement in c# for SQL - c#

I'm trying to writing a basic c# program that read datas from SQL and writes results on 3 textboxes and a label. Here is my code;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace PLAKA
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=TESTDB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Project where ID = '" + textBox1.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
textBox1.Text = dt.Rows[0][0].ToString();
textBox2.Text = dt.Rows[0][1].ToString();
textBox3.Text = dt.Rows[0][2].ToString();
textBox4.Text = dt.Rows[0][3].ToString();
SqlDataAdapter oks = new SqlDataAdapter("SELECT * FROM Project where Status = 'YES'", con);
if (oks)
{
label1.Text = "POSITIVE";
}
else
{
label1.Text = "NEGATIVE";
}
}
}
}
I'm writing ID number and see the informations of this ID on text boxes in my first part of my code and this works perfectly
All i need that when value in the 'Status' raw is "YES", my program writes "POSITIVE", other else writes 'NEGATIVE' on label1
Meanwhile Status information writes on Textbox3.
For this code i got this error message: "Error 1 Cannot implicitly convert type 'System.Data.SqlClient.SqlDataAdapter' to 'bool'
How can i solve this problem?

Your If condition is wrong.
use this.
SqlDataAdapter oks = new SqlDataAdapter("SELECT * FROM Project where Status = 'YES'", con);
oks.fill(dataSet)
if (dataSet.Tables["Table"].Rows.Count > 1)
{
label1.Text = "POSITIVE";
}
else
{
label1.Text = "NEGATIVE";
}

Related

Error when trying to update DataGridView using Microsoft Access

I am trying to show records in a DataGridView using Microsoft Access 2010. But the problem is each time i click on the button1 i get an error saying "The ConnectionString property has not been initialized"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Attendance_Generation_System
{
public partial class Take_attendance : Form
{
OleDbConnection conn = new OleDbConnection();
public Take_attendance()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
conn.ConnectionString=#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\UNI WORK\7th Semester\Visual Programming\Database31.accdb; " + "User id = admin; " + "Password = "; ;
OleDbCommand cmd =new OleDbCommand("SELECT * FROM Attendancerecord");
OleDbDataAdapter add = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
add.Fill(dt);
dataGridView1.DataSource=dt;
cmd.ExecuteNonQuery();
}
}
}
The error is clear that tells you the connection string is not assigned. So, you should assign the connection string for OleDbDataAdapter
var connectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\UNI WORK\7th Semester\Visual Programming\Database31.accdb; " + "User id = admin; " + "Password = ";
using (var oledbCnn = new OleDbConnection(connectionString))
{
oledbCnn.Open();
var cmd = new OleDbCommand("SELECT * FROM Attendancerecord", oledbCnn);
OleDbDataAdapter add = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
add.Fill(dt);
dataGridView1.DataSource = dt;
oledbCnn.Close();
}

MySQL C# - MySql.Data.MySqlClient.MySqlException

i just followed a tutorial and now is stucked with a "MySql.Data.MySqlClient.MySqlException" - Exception and "Unable to connect to any of the specified MySQL hosts".
What is causing those? The Credentials are all right.
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;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
MySqlConnection con = new MySqlConnection(#"Data Source=appm52;port=3306;Initial Catalog=test;User Id=skaratekedb;password=***");
int i;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from login where username = '" + textBox1.Text + "' and password= '" + textBox2.Text + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
label3.Text = "you have entered invalid username pr password";
}
else
{
this.Hide();
Form2 fm = new Form2();
fm.Show();
}
con.Close();
}
}
}

A error appeared in the code in VS 2015

I seem to have a problem with VS 2015.
It gets me the same error and i don't know why. I inserted below the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox2.PasswordChar = '*';
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void LogIn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Gigabyte\\Desktop\\apps\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf;Integrated Security=True");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT Status FROM Login1 WHERE Username'" + textBox1.Text + "'AND Parola='" + textBox2.Text + "' ", con);
con.Close();
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if(dt.Rows.Count==1)
{
Form2 ss = new Form2();
ss.Show();
}
}
}
}
The Application form stopped at the line with the sda.Fill(dt); and shows me this error:
Blockquote An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Blockquote
Additional information: Incorrect syntax near 'aa'.
Any help it is great! Thank you in advance!
Edit:
Problem Solved!
You are missing an = sign in your sql.
Additionally, you should be sanitizing your database inputs by using SqlParameters, not concatinating a string. You're setting yourself up for SQL Injection if you continue with your implementation.
One other optimization is that the SqlDataAdapter automatically manages your SqlConnection, so you don't need to call Open() or Close() when using Fill()
var cmd = new SqlCommand();
cmd.CommandText = "SELECT Status FROM Login1 WHERE Username = #username AND Parola= #parola";
cmd.Parameters.AddWithValue("#username", textbox1.Text);
cmd.Parameters.AddWithValue("#parola", textbox2.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
Your string should be this I suppose :
Status FROM Login1 WHERE Username ='" + textBox1.Text + "' AND Parola='" + textBox2.Text + "'
You might have missed extra spaces ;)

Object reference not set to an instance of an object error flags when running webform

I'm trying to search my database to retrieve some results and populate those to a gridview.
However, I get the above error in the title, and some research hasn't really helped me on why this kind of error flags, and was wondering whether someone with a sharper mind could explain the reason for this error. My code for the code behind file of the specific page is shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace StarksComics
{
public partial class search : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
string b = "";
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString; // the error occurs at this line. ---- nullreference exception was unhandled by code.
if (con.State == ConnectionState.Closed)
{
con.Open();
}
}
private void user_chk()
{
string a;
a = TextBox1.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbCharacters where CharName like'" + a + "%'";
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
rep_bind();
GridView1.Visible = true;
TextBox1.Text = "";
}
else
{
GridView1.Visible = false;
b = TextBox1.Text + "is not available in list";
TextBox1.Text="";
}
}
private void rep_bind()
{
string a;
a = TextBox1.Text;
SqlDataAdapter adp = new SqlDataAdapter("select * from tbCharacters where CharName like'" + a + "%'",
ConfigurationManager.ConnectionStrings["DBVS"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
user_chk();
}
}
}
once again, thank you all kindly for reviewing my code. (I've commented out the line, it's just not visible unless you drag the bar, in the page load method.)
Obviously it can't find the connection string DBVS.
Check your web.config whether it exists.
Try this code to check for null on the connection:
ConnectionString connStr = ConfigurationManager.ConnectionStrings["DBVS"];
if (connStr == null)
{
throw new Exception("Cannot find connection string DBVS in web.config");
}

custom query for datagridview

I am currently building an application in C#. In this application, people give values in a label and ​​that values will be saved in a database. This also works at the moment. What I want is the following:
The people can see their own values back in a datagridview. If I do this with the wizard of the datagridview I can't select label2.Text(this is the customerID).
The query I used below is the following:
SELECT * FROM prestaties WHERE gebruikerid = '" + label1.Text + "'";
But it doesn't work. I don't see anything in my datagrid.
Sorry for my bad English. I hope you can understand me.
The code below I already have, but it doesn't work
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Eindopdracht
{
public partial class resultaten : Form
{
public resultaten()
{
InitializeComponent();
dataGridView1.Show();
}
private string username;
public void displaydata(String ddata)
{
OleDbConnection conn = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string select = "SELECT * FROM prestaties WHERE gebruikerid = '" + label2.Text + "'";
conn.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(select, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.DataSource = ds.tables[0];
conn.Close();
}
public void setUsername(String name)
{
username = name;
label1.Text = username;
setID();
}
public void setID()
{
OleDbConnection vcon = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string selectie = "SELECT id FROM inlog WHERE Username='" + label1.Text + "'";
OleDbCommand vcom1 = new OleDbCommand(selectie, vcon);
vcon.Open();
vcom1.ExecuteNonQuery();
OleDbDataReader dr = null;
dr = vcom1.ExecuteReader();
while (dr.Read())
{
var waarde = dr.GetValue(0);
label2.Text = waarde.ToString();
}
I don't know if my code is 100% correct. I've build this by myself. If I use the class displayData in the begin next to InitializeComponent(); I will get an error.

Categories