I am having a problem with the following code:
namespace Elite_Shop
{
public partial class Bill : Form
{
int j;
int total = 0;
SqlConnection sqlcon = new SqlConnection(#"Data Source=HP\SQLEXPRESS;Initial Catalog=EliteShop;Integrated Security=True ");
public Bill()
{
InitializeComponent();
}
public void get_value(int i)
{
j = i;
}
private void Bill_Load(object sender, EventArgs e)
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
}
sqlcon.Open();
DataSet1 ds = new DataSet1();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Salesman_Table Where SMID="+j+"";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds.DataTable1);
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "Select * from Sale_Table Where OrderID=" + j + "";
cmd2.ExecuteNonQuery();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(ds.DataTable2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
total = total + Convert.ToInt32(dr2["Sub Total"].ToString());
}
SaleReport sr = new SaleReport();
sr.SetDataSource(ds);
sr.SetParameterValue("Grand Total", total.ToString());
crystalReportViewer1.ReportSource = sr;
}
}
}
When executed, the following error message is returned:
ExecuteNonQuery: Connection property has not been initialized.
How do I fix it?
You need to set the Connection property on the SqlCommand:
cmd.Connection = sqlcon;
Related
private void button1_Click(object sender, EventArgs e)
{
{
String one = "INSERT INTO empl (e_id,f_name,l_name,address) Values (#e_id, #f_name,#l_name, #address)";
SqlCommand cmd = new SqlCommand(one, con);
cmd.CommandType = CommandType.Text;
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
cmd.Parameters.AddWithValue("#e_id", dataGridView1.Rows[i].Cells["e_id"].Value);
cmd.Parameters.AddWithValue("#f_name", dataGridView1.Rows[i].Cells["f_name"].Value);
cmd.Parameters.AddWithValue("#l_name", dataGridView1.Rows[i].Cells["l_name"].Value);
cmd.Parameters.AddWithValue("#address", dataGridView1.Rows[i].Cells["address"].Value);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
cmd.Dispose();
MessageBox.Show("Excel Upload in Datbase");
con.Close();
cmd = new SqlCommand("SELECT * FROM empl");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
I have three tables: Patient, Doctor, Diagnosis. In the Diagnosis form I have two ComboBoxes, and I need to be able to choose the names of doctor and patient through these ComboBoxes.
Code of the methods:
void populatecombo()
{
string sql = "select * from Patient";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr;
try
{
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("PatId", typeof(int));
rdr = cmd.ExecuteReader();
dt.Load(rdr);
PatId.ValueMember = "PatId";
PatId.DataSource = dt;
conn.Close();
}
catch
{
}
}
void populatedoc()
{
string mysql = "select * from Doctor";
SqlCommand cmd = new SqlCommand(mysql, conn);
SqlDataReader rdr;
try
{
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("DocId", typeof(int));
rdr = cmd.ExecuteReader();
dt.Load(rdr);
DocId.ValueMember = "DocId";
DocId.DataSource = dt;
conn.Close();
}
catch
{
}
}
string patname;
string docname;
void fetchpatientname()
{
string mysql = "select * from Patient where PatId=" + PatId.SelectedValue.ToString() + "";
SqlCommand cmd = new SqlCommand(mysql, conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
patname = dr["PatName"].ToString();
PatientTb.Text = patname;
}
}
void fetchdoctorname()
{
string str = "select * from Doctor where DocId=" + DocId.SelectedValue.ToString() + "";
SqlCommand cmd = new SqlCommand(str, conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
docname = dr["DocName"].ToString();
DocName.Text = docname;
}
}
So populatedoc and populatecombo should get the names of doctor and patient, and fetch should help to choose them from ComboBox, but it doesn't seem to work with the error:
System.Data.SqlClient.SqlException: "Incorrect syntax near '='."
Picture of the form:
Based on my test, I could not get the error you provided based on your code.
You could try to use SqlCommand.Parameters.AddWithValue method to do it.
void fetchpatientname()
{
conn.Open();
string mysql = "select * from Patient where PatId=#PatId";
SqlCommand cmd = new SqlCommand(mysql, conn);
cmd.Parameters.AddWithValue("#PatId", cmbPat.SelectedValue);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
patname = dr["PatName"].ToString();
txtPatName.Text = patname;
}
conn.Close();
}
void fetchdoctorname()
{
conn.Open();
string str = "select * from Doctor where DocId=#DocId";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.Parameters.AddWithValue("#DocId", cmbDoc.SelectedValue);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
docname = dr["DocName"].ToString();
txtDocName.Text = docname;
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
fetchdoctorname();
fetchpatientname();
}
Result:
private void namecombo_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = '" + this.namecombo.SelectedItem.ToString() + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach(DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}
}
this doesn't work at all whats the problem?
You try to do it this way, just adapt it to your needs.
string sql = "SELECT * FROM Customers WHERE LastName = #lastName AND FirstName = #firstName";
UserAccount account = UserAccount.Empty;
using (SqlCommand cmd = new SqlCommand(sql, sqlConnection))
{
SqlParameter _firstName = new SqlParameter("#firstName", SqlDbType.NVarChar);
SqlParameter _lastName = new SqlParameter("#lastName", SqlDbType.NVarChar);
_firstName.Value = account.FirstName;
_lastName.Value = account.LastName;
cmd.Parameters.Add(_firstName);
cmd.Parameters.Add(_lastName);
DataSet dataSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataSet);
if (dataSet.Tables.Count > 0)
{
if (dataSet.Tables[0].Rows.Count > 0)
{
DataRow row = dataSet.Tables[0].Rows[0];
//fill your properties with the results
}
}
adapter.Dispose();
dataSet.Dispose();
}
using (SqlConnection sqlconn = new SqlConnection(#"Data Source=DESKTOP-IIBSL6N;Initial Catalog=sales_management;Integrated Security=True"))
{
sqlconn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM Customer WHERE Name = N'" + this.customergrid.SelectedRows + "' ", sqlconn);
sqlcmd.ExecuteNonQuery();
DataTable dtbl = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcmd);
adapter.Fill(dtbl);
foreach (DataRow dr in dtbl.Rows)
{
accountnumtxtbox.Text = dr["acount_name"].ToString();
phonetxtbox.Text = dr["phone_number"].ToString();
officenumtxtbox.Text = dr["office_number"].ToString();
addresstxtbox.Text = dr["Address"].ToString();
}
sqlconn.Close();
}
in my program when i delete a record, it deleted from database access and from the DataGridView , but when i close the window and open it again the record appear again in DataGridView ,Although it deleted from database access ,Here is my code :
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
command.Connection = connection;
string query = " delete from Hoteldb where ID= " +textBox0.Text + "";
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
public void BindGridView()
{
string strSQL = "SELECT * FROM Hoteldb";
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
DataTable table = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(table);
dataGridView1.DataSource = table;
connection.Close();
}
Try this :
private void button1_Click(object sender, EventArgs e)
{
int RowsAffected = 0;
connection.Open();
string query = "DELETE FROM Hoteldb WHERE ID=#ID";
command = new OleDBCommand(query);
command.Connection = connection;
cmd.Parameters.Add(new OleDbParameter("#ID", OleDbType.WChar, 150, "ID"));
cmd.Parameters["#ID"].Value = textBox0.Text.Trim()
RowsAffected = command.ExecuteNonQuery();
if(RowsAffected > 0)
{
MessageBox.Show("Guest Checked Out succesfly");
BindGridView();
}
else
{
MessageBox.Show("There was nothing to be deleted");
}
}
public void BindGridView()
{
connection.Open();
string strSQL = "SELECT * FROM Hoteldb";
cmd = new OleDbCommand(strSQL);
cmd.Connection = connection;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Hoteldb");
dataGridView1.DataSource = ds.Tables["Hoteldb"].DefaultView
connection.Close();
}
I am trying to debug the above error. Below is my code.
private SqlConnection SQLConn(string name)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return conn;
}
protected void rb2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn = SQLConn("Plastics");
try
{
string selectSQL = "SELECT [Description], [Code], [Change] FROM [plastics]";
SqlCommand cmd = new SqlCommand(selectSQL, conn);
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
catch (SqlException Exception)
{
// catch exception
Response.Write("An error occured");
}
finally
{
conn.Close();
}
}
I get an error on GridView1.DataSource = cmd.ExecuteReader();
What must I instantiate?
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
ds.Tables.Add(dt);
string str = "User ID=username;Password=password;Data Source=Test";
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from table_name";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt!=null)
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
}