Iam trying to insert integer value into access database but its giving me Object cannot be cast from DBNull to other types. error but in datagridview im putting a value but still show me this error
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability =Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value);
if (dataGridView1.IsCurrentRowDirty)
{
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string cmd1 = "insert into Medicine_Available_Detail(Medicine_Name,Dealer_name,Availability) values(#Medicine_Name,#Dealer_name,#Availability)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Medicine_Name",Medicine_Name);
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
cmd.Parameters.AddWithValue("#Availability", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
The "pencil" indicates that the row is being edited, thus - even with an entered value of 2 - the value of Availability can very well be null.
So your concept seems faulty; you should not attempt to insert data when dataGridView1.IsCurrentRowDirty is true but when it is false.
Finally got a solution on this i change my code dataGridView1_RowLeave to dataGridView1_CellValueChanged and its working fine
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
med_id = dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString();
if (med_id == "")
{
med_id1 = 0;
}
else
{
med_id1 = Convert.ToInt32( dataGridView1.Rows[e.RowIndex].Cells["Med_id"].Value.ToString());
}
if (med_id1 == 0)
{
try
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
string cmd1 = "insert into Medicine_Available_Detail(Medicine_Name,Dealer_name,Availability) values(#Medicine_Name,#Dealer_name,#Availability)";
OleDbCommand cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Medicine_Name", Medicine_Name);
cmd.Parameters.AddWithValue("#Dealer_name", Dealer_name);
cmd.Parameters.AddWithValue("#Availability", Availability);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Load_data();
dataGridView1.Refresh();
}
catch (Exception ex)
{
}
}
else
{
string Medicine_Name = dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString();
string Dealer_name = dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString();
int Availability = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString());
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd = con.CreateCommand();
cmd.CommandText = "update Medicine_Available_Detail set Medicine_Name='" + dataGridView1.Rows[e.RowIndex].Cells["Medicine_Name"].Value.ToString() + "',Dealer_name='" + dataGridView1.Rows[e.RowIndex].Cells["Dealer_name"].Value.ToString() + "',Availability='" + Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["Availability"].Value.ToString())+ "'where Med_id=" + med_id1 + "";
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Updated Successfully", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Load_data();
dataGridView1.Refresh();
}
}
Related
I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.
if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
MessageBox.Show("Please Select Data");
} else {
String query = "Select * from Attendance where empIn=#empIn";
MySqlCommand cmd1 = new MySqlCommand(query, con);
cmd1.Parameters.AddWithValue("empIn", label2.Text);
MySqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
MessageBox.Show("This Person has already IN");
} else {
insert();
}
}
}
public void insert()
{
int i;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label3.Text;
i = cmd.ExecuteNonQuery();
if (i > 0) {
MessageBox.Show("Data Inserted");
label2.Text = "";
label3.Text = "";
label4.Text = "";
} else {
MessageBox.Show("Not Deleted");
}
con.Close();
you can simply use the "using" state which will create and close the connection automatically
public object getQueryScaller(string sqlQuery)
{
object value = null;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
value = cmd.ExecuteScalar();
}
}
return value;
}
This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.
Hi i'm trying to changing the password so the user's password is update on the database. For example, i want the user Mary Tan's password to be changed from 12345 to 54321. But if affect the rest of the user's password. I really idk how to fix it.
Output:
click here
Table
database table
My Code:
protected void btnChangePassword_Click(object sender, EventArgs e)
{
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd";
if (Session["Username"] != null)
{
sql += " WHERE UserName='" + Session["Username"].ToString() + "'";
}
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
conn.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch(Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
Which means your Session["Username"] is null at this moment of execution. Hence the Where condition will skip and update all rows. And What is the Function of Reader There? It is not necessary, The ExecuteNonQuery is enough to do this Job and it will returns the number of rows affected. So you can do this in the following way:
string connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
if (Session["Username"] != null)
{
string sql = "UPDATE Staff Set Password=#NewPwd WHERE UserName=#Username";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#Username", Session["Username"]);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
}
}
else
{
// Show message that Session is Empty Can't Proceed
}
Important Note :- Don't save password as plain Text, Hash and salt them
Change your method like this (check Session in the start)
protected void btnChangePassword_Click(object sender, EventArgs e)
{
if (Session["Username"] == null)
{
//User is not logged-in. Display message or handle
return;
}
SqlDataReader dr = null;
connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;
conn = new SqlConnection(connectionString);
string sql = "UPDATE Staff Set Password=#NewPwd Where UserName = #UserName";
string newPwd = tbNewPassword.Text;
try
{
cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#NewPwd", tbNewPassword.Text);
cmd.Parameters.AddWithValue("#UserName", Session["Username"].ToString());
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((tbNewPassword.Text == dr["newPwd"].ToString()))
{
}
}
dr.Close();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
lblOutput.ForeColor = System.Drawing.Color.Green;
lblOutput.Text = "Password has been changed successfully";
}
else
{
lblOutput.ForeColor = System.Drawing.Color.Red;
lblOutput.Text = "Password does not match with our database records.";
}
}
catch (Exception ex)
{
lblOutput.Text = "Error Message: " + ex.Message;
}
finally
{
if (conn != null)
conn.Close();
}
}
try
{
UserMaster ObjUserMst = new UserMaster();
ObjUserMst.GetData("UPDATE MemberDetails SET Active = 0 WHERE Member_No = '" + txtmemberno.Text + "'");
MessageBox.Show("Installment Close Successfully.", "Close Installment", MessageBoxButtons.OK, MessageBoxIcon.Information);
btndebit.Visible = true;
btndebit.Visible = false;
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message.ToString(), "btncloseinstallment_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
its get data code
public DataTable GetData(string Query)
{
string cn = GlobalClass.ConnectionStringGet();
Con = new SqlConnection(cn);
cmd = new SqlCommand();
cmd.Connection = Con;
if (cmd.Connection.State == ConnectionState.Closed)
{
cmd.Connection.Open();
}
SqlTransaction ObjTrans = cmd.Connection.BeginTransaction();
cmd.Transaction = ObjTrans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
cmd.CommandTimeout = 500;
SqlDataReader dreader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dreader);
Con.Close();
Con.Dispose();
return dt;
}
i have winforms.
i have memberdetails Table - in this Active Field & its datatype is BIT. its
default value is 1. but i need to update it to 0.
1 = ture
0 = false
when i tried above code Active Field data didnt update
but i got message "Installment Close Successfully."
http://i.stack.imgur.com/mkuhW.png
http://i.stack.imgur.com/ToXFV.png
I upload my images on above link
help me guys.. sorry if i didnt explain very well bcz i m new here
ok i got it.
string constring = GlobalClass.ConnectionStringGet();
string sqlUpdate = "UPDATE MemberDetails SET Active = '0' WHERE Member_No = '" + txtmemberno.Text + "'";
SqlConnection conDatabase = new SqlConnection(constring);
SqlCommand cmdd = new SqlCommand(sqlUpdate, conDatabase);
conDatabase.Open();
cmdd.ExecuteNonQuery();
conDatabase.Close();
MessageBox.Show("Installment Close Successfully.");
its update Active Field 1 to 0 successfully.
I have this basic WinForms application user interface:
And I want to add the data both to the DataGridView and the sql table, when the "Gem" button is clicked. I have this following code:
private void Form2_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
con.Open();
//adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";
adap = new SqlDataAdapter(sql, con);
ds = new System.Data.DataSet();
adap.Fill(ds, "ProduktTable");
dataGridView1.DataSource = ds.Tables["ProduktTable"];
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
string navn = textBox2.Text;
int varenr = int.Parse(textBox3.Text);
float antal = (float)Convert.ToDouble(textBox4.Text);
string enhed = textBox5.Text;
string konto = comboBox2.Text;
float pris = (float)Convert.ToDouble(textBox6.Text);
dataGridView1.Rows[0].Cells[0].Value = navn;
dataGridView1.Rows[0].Cells[1].Value = varenr;
string StrQuery;
try
{
SqlCommand comm = new SqlCommand();
comm.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName ProduktTable ("
+ dataGridView1.Rows[i].Cells["Varenr"].Value + ", "
+ dataGridView1.Rows[i].Cells["Antal"].Value + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This is just an example with the purpose for storing the string "navn" and the integer "Varenr" in the DataGridView and the sql. When Im running the application and clicking on the button, following error occurs:
What's wrong with the procedure ?.
Thanks in advance
The format for an insert name doesn't require the words tableName. It wants the actual table name.
INSERT INTO tableName ProduktTable
should be
INSERT INTO ProduktTable
assuming Produ**K**tTable isn't a typo.
I am making a booking system.
I can't figure out the validation algorithm for a series of data before it insert to DB.
The primary key will be the booking ID which is automatic generate by the system.
I need to validate the bdate, btime and sname. (bdate=booking time, btime=booking time, and sname=staff name)
In case of the bdate, btime and sname is same as what the client input. the system will alert its duplicate as the staff already have booking on the same date and time.
Please find my insert query at below and appreciated you can point me to the right way.
private void btn_save_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
//query for duplicate
cmd.CommandText = "select count(*) from Booking where sname = #newName and bdate = #newDate and btime = #newTime";
// cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
//cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
// cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.CommandText = "insert into Booking(cname, bdate, btime, ccontact, sname) Values('" + txt_cname.Text + "','" + dtp_bdate.Value.Date + "','" + dtp_btime.Value.ToString("hh:mm tt") + "','" + txt_ccontact.Text + "','" + txt_sname.Text + "')";
cmd.Connection = myCon;
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
if (recordCount>0)
{
// handle duplicates
MessageBox.Show("Duplicated", "My Application",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
// cmd.Connection = myCon;
//myCon.Open();
//cmd.ExecuteNonQuery();
//myCon.Close();
//MessageBox.Show(dtp_bdate.Value.ToString());
//MessageBox.Show("Booking completed", "My Application",
// MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
private bool RecordExists(string name, DateTime date, string time)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
//query for duplicate
cmd.CommandText = "select count(*) from Booking where sname = #newName and bdate = #newDate and btime = #newTime";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
return recordCount > 0;
}
private void btn_save_Click(object sender, EventArgs e)
{
if (RecordExists(txt_cname.Text, dtp_bdate.Value.Date, dtp_btime.Value.ToString("hh:mm tt"))
{
MessageBox.Show("Duplicated", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
return;
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Booking(cname, bdate, btime, ccontact, sname) Values(#newName, #newDate, #newTime, #newContact, #newSName)";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.Parameters.Add("#newContact", OleDbType.VarChar).Value = txt_ccontact.Text;
cmd.Parameters.Add("#newSName", OleDbType.VarChar).Value = txt_sname.Text;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
MessageBox.Show(dtp_bdate.Value.ToString());
MessageBox.Show("Booking completed", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
you'll need to check if the booking exists before performing your insert, so you need to add an additional step:
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from booking where cname = #newName and bdate = #newDate and ctime = #newTime";
cmd.Parameters.Add("#newName", OleDbType.VarChar).Value = txt_cname.Text;
cmd.Parameters.Add("#newDate", OleDbType.DBDate).Value = dtp_bdate.Value.Date;
cmd.Parameters.Add("#newTime", OleDbType.VarChar).Value = dtp_btime.Value.ToString("hh:mm tt");
cmd.Connection = myCon;
myCon.Open();
int recordCount = Convert.ToInt32(cmd.ExecuteScalar());
myCon.Close();
if (recordCount>0)
{
// handle duplicates
}
when you execute this, it will either return the number of matching rows, if this is 1 or more, then you should then invoke your duplicate logic.
edited to correct code
To check if there's existing field you can make a Select and then compare:
bool InfoRepeated()
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("SELECT cname FROM yourTable;");
cmd.Connection = myCon;
myCon.Open();
try
{
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (txt_cname.Text.Equals((rdr[0].ToString())))
{
myCon.Close();
return true;
}
}
myCon.Close();
return false;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
myCon.Close();
return false;
}
}
Let me know if it works or the error you get.
working useful code try this
BOMaster obj_data = new BOMaster();
obj_data.productid = tempid;
obj_data.categoryid =int.Parse(cmbcategory.SelectedValue.ToString());
obj_data.productcode = txtproductcode.Text;
obj_data.productname = txtproductname.Text;
obj_data.mqty = decimal.Parse(txtmqty.Text.ToString());
OleDbCommand mycmd = new OleDbCommand("select * from productmaster where productname=?", new OleDbConnection(Common.cnn));
BOMaster obj_datan = new BOMaster();
mycmd.Parameters.Add(new OleDbParameter("productname", txtproductname.Text));
mycmd.Connection.Open();
OleDbDataReader myreader = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
if (myreader.HasRows == true)
{
// savestutus = "false";
MessageBox.Show("Product Name Already Exist", "Product", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtproductname.Focus();
return;
}
mycmd.Connection.Close();
ProductDAL obj_dal = new ProductDAL();
if (obj_dal.Save(obj_data))
{
Clear();
}