System.InvalidCastException - Specified cast is not valid exception - c#

Working with a mysql dbase and c#,
Below is the method I created in database class to check if the row exists.
public int CheckRows(string query)
{
try
{
openConnection();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd = new MySqlCommand(query, con);
int read = (Int32)cmd.ExecuteScalar();
return read;
cmd.Dispose();
closeConnection();
}
And the button click event,
private void button2_Click(object sender, EventArgs e)
{
int invoice = Convert.ToInt32(textBox9.Text);
string qry = "Select 1 from purchase where purchId='" + invoice + "'";
int dub = db.CheckRows(qry);
}
Which gives the mentioned exception. What am I doing wrong here?

Related

How to update oracle database table in c# with variable from text.box

When I click on update button I dont get any errors but my table isnt updated.
private void Button3_Click(object sender, EventArgs e)
{
try
{
OracleConnection cnn = new OracleConnection(oradb);
cnn.Open();
oracleCommand = new OracleCommand("UPDATE KUPAC SET NAZIVKUPCA = :NAZIVKUPCA, PIB = :PIB, MATICNIBROJ = :MATICNIBROJ, ZIRORACUN = :ZIRORACUN, EMAIL = :EMAIL WHERE KUPACID = :KUPACID", cnn);
oracleCommand.Parameters.Add("#KUPACID", Convert.ToInt32(txtKupacId.Text));
oracleCommand.Parameters.Add("#NAZIVKUPCA", txtNazivKupca.Text);
oracleCommand.Parameters.Add("#PIB", txtPIB.Text);
oracleCommand.Parameters.Add("#MATICNIBROJ", txtJMBG.Text);
oracleCommand.Parameters.Add("#ZIRORACUN", txtZiroRacun.Text);
oracleCommand.Parameters.Add("#EMAIL", txtEmail.Text);
int result = oracleCommand.ExecuteNonQuery();
MessageBox.Show("Kupac uspesno izmenjen");
}
catch (Exception exc)
{
MessageBox.Show("Greska prilikom izmena u bazi." + exc.Message);
}
finally
{
}
OsveziKupce();
ObrisiPolja();
}
I get message "Kupac uspesno izmenjen", which means that table should be updated, but nothing happens

Update table failure without any error

I'm current facing a strange issue that everytime i want to update my table value field from reserved to cancelled.
every time i click the button it din't pop any error but when i went to my ms-access to check it never change...
My Method:
public static void CancelClasses(int rid, int mid)
{
OleDbConnection myconnection = GetConnection();
string mysql = "UPDATE ClassesReservation SET Status = 'cancelled' WHERE ReservationID= "+rid+" AND MID="+mid+";";
OleDbCommand mycmd = new OleDbCommand(mysql, myconnection);
try
{
myconnection.Open();
mycmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
myconnection.Close();
}
}
Button Function:
protected void CancelWS_Click(object sender, EventArgs e)
{
if (ListBox3.SelectedIndex < 0)
{
Label2.Text = "Invalid Submit! Please select an Class or Workshop";
}
else
{
int reid = int.Parse(ListBox3.SelectedValue);
int MID = Convert.ToInt32(Session["memberid"]);
DBconn.CancelClasses(reid, MID);
}
}

How to insert data into two SQL Server tables in asp.net

I have two tables, the first table is Course and this table contains three columns Course_ID, Name_of_course, DeptID; and the second table is Department and it has three columns DeptID, DepName, College.
I put a GridView to display the data that I will add it. But when I write the command to insert the data in both tables the data don't add. I used this command
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GridViewRow r = GridView1.SelectedRow;
Dbclass db = new Dbclass();
string s = "";
DataTable dt = db.getTable(s);
ddcollege.SelectedValue = dt.Rows[0]["College"].ToString();
dddept.SelectedValue = dt.Rows[1]["DepName"].ToString();
tbid.Text = r.Cells[0].Text;
tbcourse_name.Text = r.Cells[1].Text;
lblid.Text = tbid.Text;
lberr.Text = "";
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
protected void btadd_Click(object sender, EventArgs e)
{
try
{
if (tbid.Text == "")
{
lberr.Text = "Please input course id";
return;
}
if (tbcourse_name.Text == "")
{
lberr.Text = "Please input course name";
return;
}
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s = "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Dbclass db = new Dbclass();
if (db.Run(s))
{
lberr.Text = "The data is added";
lblid.Text = tbid.Text;
}
else
{
lberr.Text = "The data is not added";
}
SqlDataSource1.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
lberr.Text = ex.Message;
}
}
Here is the Dbclass code:
public class Dbclass
{
SqlConnection dbconn = new SqlConnection();
public Dbclass()
{
try
{
dbconn.ConnectionString = #"Data Source=Fingerprint.mssql.somee.com;Initial Catalog=fingerprint;Persist Security Info=True;User ID=Fingerprint_SQLLogin_1;Password=********";
dbconn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//----- run insert, delete and update
public bool Run(String sql)
{
bool done= false;
try
{
SqlCommand cmd = new SqlCommand(sql,dbconn);
cmd.ExecuteNonQuery();
done= true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
//----- run insert, delete and update
public DataTable getTable(String sql)
{
DataTable done = null;
try
{
SqlDataAdapter da = new SqlDataAdapter(sql, dbconn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return done;
}
}
Thank you all
The main thing I can see is you are assigning two different things to your "s" variable.
At this point db.Run(s) the value is "Insert into Department etc" and you have lost the first sql string you assigned to "s"
Try:
string s = "Insert into Course(Course_ID,Name_of_course) values ('" + tbid.Text + "','" + tbcourse_name.Text + "')";
s += "INSERT INTO Department (DepName,College,DeptID) VALUES ('"+dddept.SelectedValue+"','"+ddcollege.SelectedValue+"','"+tbdeptID.Text+"')";
Notice the concatenation(+=). Otherwise as mentioned above using a stored procedure or entity framework would be a better approach. Also try to give your variables meaningful names. Instead of "s" use "insertIntoCourse" or something that describes what you are doing
When a value is inserted into a table(Table1) and and value has to be entered to into another table(Table2) on insertion of value to Table1, you can use triggers.
https://msdn.microsoft.com/en-IN/library/ms189799.aspx
"tbdeptID.Text" is giving you the department Id only right? You should be able to modify your first statement
string s = "Insert into Course(Course_ID,Name_of_course,) values ('" + tbid.Text + "','" + tbcourse_name.Text + "',)";
Please start running SQL Profiler, it is a good tool to see what is the actual query getting executed in server!

DataSet not updated with new row inserted in C#

i am trying to insert new row in Emp table in c# (disconnected mode), the new row successfully inserted but the dataset not updated, so when i search for the new row, i don't find it, but when i search for an old row, i find it.
the insertBTN button used to insert new row
the searchByID button used to search for row by its ID
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private SqlConnection conn;
private SqlDataAdapter adapter;
private DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
conn = new SqlConnection(#"data source=(local);initial catalog =Test;integrated security = true");
conn.Open();
adapter = new SqlDataAdapter("select * from Emp",conn);
ds = new DataSet();
adapter.Fill(ds,"Emp");
}
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
string name = textBox2.Text;
string address = textBox3.Text;
int age = int.Parse(textBox4.Text);
int salary = int.Parse(textBox5.Text);
SqlCommand command = new SqlCommand("Insert into Emp values(" + id + ",'" + name + "','" + address + "'," + age + "," + salary + ")", conn);
command.ExecuteNonQuery();
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
foreach (DataRow row in ds.Tables["Emp"].Rows)
{
if (Convert.ToInt32(row["id"]) == id)
{
textBox2.Text = Convert.ToString(row["name"]);
textBox3.Text = Convert.ToString(row["address"]);
textBox4.Text = Convert.ToString(row["age"]);
textBox5.Text = Convert.ToString(row["salary"]);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The Update method of the DataAdapter doesn't read again but tries to execute the INSERT, DELETE and UPDATE commands derived from the original SELECT statement against the Rows in the DataTable that have their RowState changed
So, if you want to use the Update method of the adapter you could write
private void insertBTN_Click(object sender, EventArgs e)
{
try
{
DataRow row = ds.Tables["emp"].NewRow();
row.SetField<int>("id", int.Parse(textBox1.Text));
row.SetField<string>("name", textBox2.Text));
row.SetField<string>("address", textBox3.Text));
row.SetField<int>("age", int.Parse(textBox4.Text));
row.SetField<int>("salary", int.Parse(textBox5.Text));
ds.Tables["emp"].Rows.Add(row);
adapter.Update(ds,"Emp");
MessageBox.Show("Employee added successfully");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
At this point your DataSet contains the added row because you have added it manually and then passed everything to the Update method to write it to the database.
However, keep in mind that the Update method to work requires certain conditions to be present. You could read them in the DbDataAdapter.Update page on MSDN.
Mainly you need to have retrieved the primary key of the table, do not have more than one table joined together and you have used the DbCommandBuilder object to create the required commands (Again the example in the MSDN page explain it)
Not related to your question, but you could change your search method and avoid writing a loop to search for the ID
private void searchByID_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(textBox1.Text);
DataRow[] foundList = ds.Tables["Emp"].Select("Id = " + id);
if(foundList.Length > 0)
{
textBox2.Text = foundList[0].Field<string>("name");
textBox3.Text = foundList[0].Field<string>("address");
textBox4.Text = foundList[0].Field<int>("age").ToString();
textBox5.Text = foundList[0].Field<int>("salary").ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

how to retrieve record of selected item of combobox in to the text box

I want to show all details of the member through the name selected in combo box..Im trying below given code
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
con.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT FlatNo FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
tbOwnerName.Text = ((string)cmd.ExecuteScalar());
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
I understand that you need to get all column records from memberinfo table and display them in UI. For that, you need to use ExecuteReader instead of ExecuteScalar. I have implemented execute reader in below code
private void cbSearchByName_SelectedIndexChanged(object sender,EventArgs e)
{
try
{
//int RowsAffected = 0;
DataAccess oDataAccess = new DataAccess();
using(SqlConnection connection = con )
{
connection.Open();
//showing flat number of selected member by name
oDataAccess.cmd.CommandText = "SELECT Top 1 Name,City FROM MemberInfo where MemberName='" + cbSearchByName.Text + "'";
oDataAccess.cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
tbOwnerName.Text = dr["Name"].ToString();
tbOwnerCity.Text = dr["City"].ToString();
//similarly store other column values in respective text boxes or wherever you need to get it displayed.
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Categories