I'm trying to make an agenda facility for my winform project. I want to display database records on textBox for specific date when user chose date on monthCalendar control. Below you can see my db table design, my winform design and my code and exception message that i'm getting. How can i fix this?
*ps: no need to suggest on using parametrized queries. i can and i will change it eventually
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 EKS
{
public partial class Agenda : Form
{
public Agenda()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.BackColor = Color.FromArgb(100, 88, 55, 55);
}
private void button1_Click(object sender, EventArgs e)
{
try {
string myQuery = "insert into agenda (input_agenda, input_date) values ('"+textBox1.Text.ToString()+"', '"+ monthCalendar1.SelectionStart +"')";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = myQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("agenda updated");
}
catch (Exception x) {
MessageBox.Show(x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try {
string deleteQuery = "DELETE FROM agenda WHERE input_date = '" + monthCalendar1.SelectionStart +"'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = deleteQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("delete succeeded");
}
catch(Exception x){
MessageBox.Show(x.ToString());
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
GetAgendaDetails(e.Start.Date);
}
private void GetAgendaDetails(DateTime x){
string myQuery = "select input_agenda from agenda where input_date = '" + x.Date.ToString() + "'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
try {
myConn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
textBox1.Text = myReader.GetString(100);
}
myConn.Close();
}
catch(Exception z){
MessageBox.Show(z.ToString());
}
}
}
}
Use DateSelected event of MonthCalendar control, Which will be fired when user selects a date.
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
AganedaInformation info = GetAgendaDetails(e.Start.Date);
}
Add a private method to query the database based on the passed selected date
Private AganedaInformation GetAgendaDetails(DateTime selectedDate)
{
//Add logic to query the database with the selected date and return the information
}
Related
I need to build a application where people can make a reservation but before doing that they need to fill in some information. I get this error code at the moment when i try to save the data: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BonTemps
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var Form1 = new Form1();
Form1.Show();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Home_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bonTempsDBDataSet.Tafel' table. You can move, or remove it, as needed.
this.tafelTableAdapter.Fill(this.bonTempsDBDataSet.Tafel);
}
private void btnOpslaan_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = (#"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres), VALUES ('" + txtNaam.Text + "','" + txtAdres.Text + "','" + txtWoon.Text + "','" + txtTel.Text + "','" + txtMail.Text + "'");
com.ExecuteNonQuery();
sc.Close();
}
}
}
Remove the comma Before VALUES.
If that is not enough, you can debug and copy the generated string from Command Text and try running it directly in SQL Server Mangement Studio or similar
A typographical error remove the COMMA before the word VALUES.
You have to pass an open SqlConnection to your SqlCommand to make it work:
com.Connection = sc;
Also, consider using named parameters to pass data to your query to make your query more error-proof:
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = #"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres) VALUES (#naam, #adres, #woon, #tel, #mail)";
com.Parameters.AddWithValue("#naam", txtNaam.Text);
com.Parameters.AddWithValue("#adres", txtAdres.Text);
com.Parameters.AddWithValue("#woon", txtWoon.Text);
com.Parameters.AddWithValue("#tel", txtTel.Text);
com.Parameters.AddWithValue("#mail", txtMail.Text);
com.ExecuteNonQuery();
sc.Close();
using (var sc = new SqlConnection("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True"))
{
using (var com = new SqlCommand("sql cmd text", sc))
{
try
{
sc.Open();
com.ExecuteNonQuery();
}
catch
{
}
}
}
I have problem with Arabic character display in textbox using SQL database. I use the nvarchar type in SQL and when I select a Latin character in item combobox its work perfectly (img1), but when i try to select an Arabic item in combobox nothing happen in textbox 1 and 2 (img2).
The code :
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.Sql;
using System.Data.SqlClient;
namespace testconnection
{
public partial class Form1 : Form
{
private SqlConnection con;
private SqlCommand cmd;
private SqlDataAdapter da;
private DataTable dt;
private SqlDataReader dr;
public Form1()
{
InitializeComponent();
combo();
}
void combo()
{
con = new SqlConnection(
#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\vemmi\Documents\user.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("SELECT usrs FROM usrtest", con);
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr["usrs"]);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 c = new Form2();
c.ShowDialog();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con = new SqlConnection(
#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\vemmi\Documents\user.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("SELECT * FROM usrtest WHERE usrs like '" + comboBox1.Text + "' ");
cmd.Connection = con;
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string p = dr["pwd"].ToString();
string n = dr["nbr"].ToString();
textBox2.Text = p;
textBox3.Text = n;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
enter image description here
Try adding 'N' before the Arabic string in the query.
cmd = new SqlCommand("SELECT * FROM usrtest WHERE usrs like N'" + comboBox1.Text + "' ");
I have the following code.
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;
namespace SalesSystem
{
public partial class Order : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local);Initial Catalog=MOE;Integrated Security=True";
conn.Open();
SqlCommand da = new SqlCommand("Select Itemid,ItemName from Item", conn);
DropDownList1.DataSource = da.ExecuteReader();
DropDownList1.DataTextField = "Itemname";
DropDownList1.DataValueField = "Itemid";
DropDownList1.DataBind();
conn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
string orderdate = txtorderdate.Text;
string customerid = txtcustomerid.Text;
string itemid = DropDownList1.SelectedValue;
string qty = txtquantity.Text;
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=(local);Initial Catalog=MOE;Integrated Security=True";
con.Open();
SqlCommand result = new SqlCommand("Insert Into [Order](Orderdate,Customerid,Itemid,OQty) Values ('" + orderdate + "','" + customerid + "','" + itemid + "','" + qty + "')", con);
result.ExecuteNonQuery();
}
}
}
Whenever I run this and click the "Add" button, the value of the dropdown list (itemid) is always inserted as the first value (001) not matter how many times I changed the dropdown list value.
It is rebinding after every post back. check this to make sure your drop down is bound only once during the first page load but not when you click Button
protected void Page_Load(object sender, EventArgs e)
{
try
{
if(!IsPostBack)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(local);Initial Catalog=MOE;Integrated Security=True";
conn.Open();
SqlCommand da = new SqlCommand("Select Itemid,ItemName from Item", conn);
DropDownList1.DataSource = da.ExecuteReader();
DropDownList1.DataTextField = "Itemname";
DropDownList1.DataValueField = "Itemid";
DropDownList1.DataBind();
conn.Close();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
I am trying to create a login Form. But Having Problems with database. I have created a windows form which consists of a user name and password, and a login button. But I think statement :
DataAdapterObject.Fill(DataTableObject)
has some error. I am using Visual Studio Profesional 2013 Update 4 and Sql Server 2014 Enterprise Editon.
The Code is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Society_Accounting_Software
{
public partial class LoginScreen : Form
{
SqlConnection databaseConnect = new SqlConnection();
public LoginScreen()
{
SqlConnection databaseConnect = new SqlConnection();
databaseConnect.ConnectionString = "Data Source=GAURAV-PC;Initial Catalog=SocietyAccountingDatabase;Integrated Security=True";
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection databaseConnect = new SqlConnection("Data Source=GAURAV-PC;Initial Catalog=SocietyAccountingDatabase;Integrated Security=True");
databaseConnect.Open();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged_1(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string queryString = "select UserId,UserPassword from UserAccounts where UserId='gaurav' AND UserPassword='test123'";
SqlConnection databaseConnect = new SqlConnection();
databaseConnect.ConnectionString = "Data Source=GAURAV-PC;Initial Catalog=SocietyAccountingDatabase;Integrated Security=True";
databaseConnect.Open();
string userName = UserNameTextBox.Text;
string Password = PasswordTextBox.Text;
SqlCommand SqlCommandObject = new SqlCommand("select UserId,UserPassword from UserAccounts where UserId='"+userName+"' AND UserPassword='"+Password+"'");
SqlDataAdapter DataAdapterObject = new SqlDataAdapter(SqlCommandObject);
DataTable DataTableObject = new DataTable();
DataAdapterObject.Fill(DataTableObject);
if (DataTableObject.Rows.Count > 0)
{
MessageBox.Show("Login Sucessful");
AdminConsoleForm AdminConsole= new AdminConsoleForm();
this.Hide();
AdminConsole.Show();
}
else
{
MessageBox.Show("Invalid Login Name And Password Please Try Again!");
}
databaseConnect.Close();
//AdminConsoleForm AdminConsole= new AdminConsoleForm();
//this.Hide();
//AdminConsole.Show();
}
}
}
Can any one help?
Wherever possible you should be using database connections like so.
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
//...
}
At the moment you are randomly creating connections in various methods ontop of having a connection field, this is pretty confusing.
You should not be concatenating SQL and should use parameterised queries
using(var connection= new SqlConnection(connectionString))
{
connection.Open();
var sql = #"SELECT password FROM users WHERE userid = #userid";
var command = new SqlCommand(sql, connection);
command.Parameters.Add("#userid", SqlDbType.VarChar);
command.Parameters["#userid"].Value = username;
// ....
}
Passwords should never be stored as plaintext and you should not be able to query the password 'directly'. A simple method of securing passwords is to hash the password with a random salt, storing the salt along with the hash in the database.
You don't really need a DataTable you should only have a single row returned and a DataReader is enough in this scenario.
using(var connection= new SqlConnection(connectionString))
{
connection.Open();
var sql = #"SELECT password, salt FROM users WHERE userid = #userid";
var command = new SqlCommand(sql, connection);
command.Parameters.Add("#userid", SqlDbType.VarChar);
command.Parameters["#userid"].Value = username;
using(var reader = command.ExecuteReader())
{
if (reader.Read())
{
var password = reader.GetString(0);
var salt = reader.GetString(1);
return CheckPassword(password, salt, PwrdTextBox.Text);
}
Debug.WriteLine("The user {0} does not exist", username);
return false;
}
}
I would recommend reading through this article Salted Password Hashing - Doing it Right on CodeProject.
First, as your form load, you've already instantiated a connection string and immediately open it.
Second, as user clicks the button to login, you've instantiated the same connection string and open it again, which makes the operation redundant. Because the connection state of that Database is already Open which you're trying to Open again during button click which makes the operation impossible or cannot be processed.
A Simple code for a login form:
namespace Society_Accounting_Software
{
public partial class LoginScreen : Form
{
SqlConnection databaseConnect = new SqlConnection();
public LoginScreen()
{
SqlConnection databaseConnect = new SqlConnection();
databaseConnect.ConnectionString = "Data Source=GAURAV-PC;Initial Catalog=SocietyAccountingDatabase;Integrated Security=True";
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged_1(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (!(UserNameTextBox.Text == string.Empty))
{
if (!(PasswordTextBox.Text== string.Empty))
{
//this represent your connection to database
String str = "Data Source=GAURAV-PC;Initial Catalog=SocietyAccountingDatabase;Integrated Security=True";
String query = "select * from UserAccounts where userid = '"+UserNameTextBox.Text+"'and password = '"+this.PasswordTextBox.Text+"'";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dbr;
con.Open();
dbr = cmd.ExecuteReader();
int count = 0;
while (dbr.Read())
{
count = count + 1;
}
con.Close();
if (count == 1)
{
AdminConsoleForm objmain = new AdminConsoleForm();
objmain.Show(); //after login Redirect to second window
this.Hide();//after login hide the Login window
}
else if (count > 1)
{
MessageBox.Show("Duplicate username and password", "login page");
}
else
{
MessageBox.Show(" Username and Password Incorrect", "login page");
}
}
else
{
MessageBox.Show(" Password Empty", "login page");
}
}
else
{
MessageBox.Show(" Username Empty", "login page");
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
}
I have kept the code really simple. You can do salting if you want security.
I am building a windows application using C#. In my login form, I'm getting Select Command property has not been initialized before calling fill method.
Here is the code:
public partial class frmlogin : Form
{
SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=loginerror;Integrated Security=True");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter();
public frmlogin()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = con;
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "select * from login where username='" + txt1.Text + "' and password='" + txt2.Text +"'";
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
frmmain main = new frmmain();
main.Show();
}
else
{
MessageBox.Show("Please enter correct name and passowrd", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
You have to specify select command of SqlDataAdapter before filling your table. You are not doing it. Your SqlCommand object is not connected in any way to your SqlDataAdapter.
adp.SelectCommand=cmd;
Another way to accomplish would be to simply pass the SQLCommand as an argument into your data adapter as follows -
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
SQL Data Adapter interacts with the data table. It is used to fill the Data Table from SQL Server DataBase. Before, filling the Data Table, the Data Adapter should know the command it is going to execute. So we have to fill the object of SQL Command Type i.e
SqlDataAdapter da = new SqlDataAdapter(cmd);
Here cmd is the object of SQL Command.
Now, the Data Adapter will know which command to execute before filling the data table.
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 Employees_Details_Management_System
{
public partial class ShowEmpDtlsFrm : Form
{
SqlConnection con = new SqlConnection(#"Data Source = (local); Initial Catalog = sp_emp; Integrated Security = True");
public SqlCommand cmd { get; private set; }
// private SqlCommand cmd;
public ShowEmpDtlsFrm()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
ShwEmpDtlsLbl.Text = "Employee Database Management";
comboBox1.Text = "Click";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DataGridChk()//Check if DataGrid is empty or not
{
if (dataGridView1.RowCount == 1)
{
dataGridView1.Visible = false;
MessageBox.Show("The Given " + comboBox1.Text+ " is Invalid \nEnter Valid " + comboBox1.Text);
}
}
public void DbDataFetch(String Qry)//For Fetching data from database
{
SqlCommand cmd = new SqlCommand(Qry, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
dataGridView1.DataSource = ds.Tables["emp"].DefaultView;
DataGridChk();
}
public void SrchBtn_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "Employee ID" || comboBox1.Text == "Department ID" || comboBox1.Text == "Manager ID")
{
if (textBox1.Text != "")
{
con.Open();
dataGridView1.Visible = true;
if (comboBox1.Text == "Employee ID")
{
string Qry = "select * from emp where emp_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Department ID")
{
string Qry = "select * from emp where dep_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Manager ID")
{
string Qry = "select * from emp where manager_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
con.Close();
}
else
{
MessageBox.Show("Please Enter the ID...");
}
}
else
{
MessageBox.Show("Choose Valid Option...");
}
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
EmpDtlsFrm edf = new EmpDtlsFrm();
edf.Show();
this.Hide();
}
}
}