No value given for one or more required parameters.() - c#

I have a problem, when i m login the error is occured that No value given for one or more required parameters.
protected void imgbtn_login_Click(object sender, ImageClickEventArgs e)
{
int UserId = 0;
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pathto.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "select * from Users where LoginName='" + txt_logname.Text + "' and Password='" + txt_pass.Text + "';";
OleDbDataAdapter da=new OleDbDataAdapter(query,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
try
{
UserId = Int32.Parse(dt.Rows[0]["UserId"].ToString());
//btn_LogIn.Text = "Login Succeded";
Response.Redirect("Register.aspx");
}
catch (Exception ex)
{
}
txt_logname.Text = " ";
txt_pass.Text = "";
}

Password is a reserved word. Put it in square brackets [Password]
See Syntax error in INSERT INTO statement

Related

Data Mismatch In Criteria Expression

I am trying to delete data from a Database AND the DataGridViewer using Winforms on Visual Studio. The way I am doing this is selecting a cell, and based on where that cell is, that row will be deleted. The selected row will read two strings and one date. I've tested the two strings and they work perfectly when deleting data. When it comes to the date, it doesn't seem to work for me, I keep getting an error. The error message will be attached as an image and the code will be below. I am fairly new to C# and SQL, just to put that out there.
private void delete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in daily_log.SelectedCells)
{
if (theCell.Selected)
{
string eid = daily_log[0, theCell.RowIndex].Value.ToString();
string aid = daily_log[4, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(daily_log[5, theCell.RowIndex].Value);
try
{
connection.Open();
using (OleDbCommand cmd = new OleDbCommand("DELETE FROM DailyLog WHERE EmployeeID='" + eid + "' AND ActivityID = '" + aid + "' AND Date = '" + dt.Date + "'", connection))
{
cmd.ExecuteNonQuery();
}
connection.Close();
daily_log.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
}
Is this a conversion error? And if so, how would I fix this?
You could try to use OledbParameter to delete data from access database.
Here is a code example you can refer to.
OleDbConnection conn = new OleDbConnection("connstr");
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell theCell in dataGridView1.SelectedCells)
{
if (theCell.Selected)
{
string id = dataGridView1[0, theCell.RowIndex].Value.ToString();
string aid = dataGridView1[1, theCell.RowIndex].Value.ToString();
DateTime dt = Convert.ToDateTime(dataGridView1[2, theCell.RowIndex].Value);
try
{
conn.Open();
string sql = "delete from DailyLog where ID=#ID AND AID=#AID AND Date=#Date";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#AID", aid);
cmd.Parameters.AddWithValue("#Date", dt);
cmd.ExecuteNonQuery();
}
dataGridView1.Rows.RemoveAt(theCell.RowIndex);
}
catch (Exception ex)
{
MessageBox.Show("Err: " + ex);
}
}
}
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
conn.Open();
string query = "select * from DailyLog";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(da);
var ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Result:
Your Ids are probably numeric, and Date is a reserved word, so try with:
"DELETE FROM DailyLog WHERE EmployeeID = " + eid + " AND ActivityID = " + aid + " AND [Date] = #" + dt.Date.ToString("yyyy'/'MM'/dd") + "#"
That said, go for using parameters.
{

C# Display data based on userID

Hi I'm creating a C# program where users can login and book bus seats for destinations, I have the program so users can insert/update/delete data but I want the data to just display the currently logged-in data, this is my code below.
This function is in the main dashboard class where it displays the seats table to the dataviewgrid
private void displayBookings()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
This is my database table and all I want to do once a user is logged in is display each seatID by the userID, the seatid is the primary key for this table and the userid is a foreign key linked to the userdata table.
EDIT:
private void displayBookings()
{
SqlConnection con = new SqlConnection(#"CONNECTIONSTRING");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
// the userID of the logged in user
p_userID.Value = cmd.Parameters.Add(p_userID);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Login method
private void loginButton_Click(object sender, EventArgs e)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Brandon Brock\source\repos\SE2\Booking System\Database1.mdf;Integrated Security=True"))
{
con.Open();
string str1 = "select * from userdata where username='" + log_username.Text + "' and password_1='" + log_password.Text + "'";
SqlCommand cmd = new SqlCommand(str1, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(str1, con);
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
switch (dt.Rows[0]["type"] as string)
{
case "admin":
{
MessageBox.Show("You are logged in!", "Admin Portal", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Admin().Show();
break;
}
case "user":
{
MessageBox.Show("You are logged in!", "Seat Reservation", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Dashboard().Show();
break;
}
default:
{
MessageBox.Show("Enter Correct Username and Password");
break;
}
}
log_username.Text = "";
log_password.Text = "";
}
else
{
MessageBox.Show("Username or Password is wrong or Account doesn't exist!", "Bus Seat Account Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
}
Assuming you have access to the logged in user data:
con.Open(); // <-- can't see where this comes from but is almost certainly an anti-pattern. Don't re-use SqlConnection instances, make new ones and Dispose() when done.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
p_userID.Value = // the userID of the logged in user
cmd.Parameters.Add(p_userID);
//cmd.ExecuteNonQuery(); <-- this is pointless, delete it
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();

How to resolve Invalid Object Name "Table Name" in C#?

When I am running My application in Visual Studio 2008 it is showing me Message Box with notation of Invalid Object Name "Table name", instead the table is already there in my database. So please help me to solve this problem.
private void FrmInwardDisp2_Load(object sender, EventArgs e)
{
byte _true = 1;
byte _false = 0;
//this.toolTip1.SetToolTip(this.dgvDisplay, "Double Click to Edit");
int width = Screen.PrimaryScreen.Bounds.Width;
int height = Screen.PrimaryScreen.Bounds.Height - 175;
dgvDisplay.Width = width - 25;
dgvDisplay.Height = height;
//dgvDisplay.AutoSize = true;
try
{
SqlConnection con = new SqlConnection(Variables.con);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.SelectCommand = cmd;
switch (Static_Class.selected)
{
case 1:
{
btnAddInward.Text = "Add Rental Inward";
cmd.CommandText = "SELECT [RentalInwardNo],[VoucherNo],[NameOfWork]
[Location],[NameOfVendor],[VendorCode],[VendorItemCode],[ItemName],
[Narration],[WareHouse],[DriverName],[VehicleNo],[RejectedItemCode],
[RejectedItemName],[Rate],[Date],[InvoiceNo],[ChallanNo],[TenderCode],
[PINo],[PONo],[UnitQty],[UOM],[RequisitionNo],[ReceivedBy],
[LocationID],[Layer],[Local],[Global],[DeleteStatus],[AutoGenerated]
FROM IN_Rental_Inward
where [TenderCode]= " + Static_Class.tendercode + "
and [LocationID]='" + Static_Class.LocationID + "'
and [Layer]='" + Static_Class.Layer + "'
and [DeleteStatus]=" + 0;
try
{
//con.Open();
da.Fill(ds, "TableDisplay");
da.Dispose();
cmd.Dispose();
//con.Close();
dgvDisplay.DataSource = ds.Tables["TableDisplay"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
break;
In your query text, specify the table's schema name also before the table name. For example:
cmd.CommandText = "SELECT … FROM dbo.IN_Rental_Inward …";
// ^^^^

C# Sqlite Search Multiple Tables

I'm tring to search for a value in multiple Sqlite tables and return the row where the value is found.
But my code only works if the value is in the last table i search.
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
dataGridView1.DataSource = "";
try
{
string comando = "SELECT UFE_SG, lOG_NO FROM log_logradouro where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
try
{
string comando = "SELECT UFE_SG, lOc_NO FROM log_localidade where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
try
{
string comando = "SELECT UFE_SG, CPC_NO FROM log_cpc where cep ='" + maskedTextBoxCep.Text + "'";
DB = new SQLiteDataAdapter(comando, sql_con);
}
catch (SystemException e)
{
}
DS.Reset();
DB.Fill(DS);
DT = DS.Tables[0];
dataGridView1.DataSource = DT;
sql_con.Close();
It looks like you're overwriting the DB object in each try/catch block instead of executing the query and checking for results with each command.

How can I query a DataGridView using SQL?

I need to query a DataGridView using SQL but don't show to DataGridView.
public chkTime()
{
InitializeComponent();
}
HRTaffDataContext db = new HRTaffDataContext();
SqlConnection Conn;
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da;
DataTable dt = new DataTable();
DataSet ds = new DataSet();
StringBuilder sb = new StringBuilder();
string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
string strDate;
private void chkTime_Load(object sender, EventArgs e)
{
connStr();
return;
}
public void connStr()
{
Conn = new SqlConnection();
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = appConn;
Conn.Open();
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(appConn);
string sql = "SELECT [filesTA].EmpNo,[Employee].[First Name],[filesTA].ChkDate,[filesTA].ChkIn,[filesTA].ChkOut,[CompanyData].ShortName"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ErrorCode = 0"; // It's work
+ " WHERE [filesTA].ErrorCode = 0 and [filesTA].ChkDate ='" + dateTimePicker.Text.ToString() + "'";
da = new SqlDataAdapter(sql, Conn);
DataSet ds = new DataSet();
da.Fill(ds);
Conn.Close();
dgvShow.DataSource = ds.Tables[0];
}
"WHERE [filesTA].ErrorCode = 0" works fine.
"WHERE [filesTA].ErrorCode = 0 and [filesTA].ChkDate ='" + dateTimePicker.Text.ToString() + "'" does not work.
I need to set where DateTime.
$dateTimePicker.Text returns a string for human reading and your server maybe don't like it.
Try something like:
string sql = string.Format("SELECT [filesTA].EmpNo,[Employee].[First Name],[filesTA].ChkDate,[filesTA].ChkIn,[filesTA].ChkOut,[CompanyData].ShortName"
+ " From [WebSP].[dbo].[filesTA] inner join [WebSP].[dbo].[Employee] on [Employee].EmployeeNo=[filesTA].EmpNo INNER JOIN [WebSP].[dbo].[CompanyData] On [CompanyData].Company = [Employee].Company"
+ " WHERE [filesTA].ErrorCode = 0 and [filesTA].ChkDate ='{0}-{1}-{2}'",
dateTimePicker.Value.Year,
dateTimePicker.Value.Month,
dateTimePicker.Value.Day);
You need to use dateTimePicker.Value.ToString() instead of dateTimePicker.Text.ToString()
A simple example of using this can be dateTimePicker.Value.ToString("yyyy-MM-dd")

Categories