Domanda

In datagridview I have one checkbox column ,row(s) in which checkbox is checked is/are should get deleted from datagridview as well as from database when i click on delete button ,I am using this code for doing this functionality ,using this code i am able to delete row from datagidview,but while deleting it from database i am getting this exception Data type mismatch in criteria expression. after this line of code cmd.ExecuteNonQuery(); where i am going wrong,what correction should i do so that i get this working

private void button1_Click(object sender, EventArgs e)
{

        List<int> ChkedRow=new List<int>();
        DataRow dr;
        List<int> ChkedRowQid=new List<int>();

        for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
        {
        if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["select"].Value) == true)
        {
          ChkedRow.Add(i); 
            ChkedRowQid.Add(Convert.ToInt16(dataGridView1.Rows[i].Cells["QID"].Value));

        }
        }

        foreach (int k in ChkedRow)
        {
        dr = dt.Rows[k];
        dt.Rows[k].Delete();
            foreach(int j in ChkedRowQid)
            {
                bool flag=false;
            try 
            {
                string sql = "DELETE FROM Questions WHERE QID='" + j + "' ";
                OleDbCommand cmd = new OleDbCommand(sql,acccon);
                cmd.ExecuteNonQuery();
                flag = true;
            }
            catch(Exception err)
            {

            }

            }

        //dt.Rows.Remove(dr);
        }

Thanks In advance for any help

È stato utile?

Soluzione

From your code

Convert.ToInt16(dataGridView1.Rows[i].Cells["QID"].Value) 

i can guess your QID is an integer whereas you are passing it as a string. You dont need single quotes around it.

string sql = "DELETE FROM Questions WHERE QID=" + j ;

should be good.

Edit:

Although this should work for you but this is not a recommended practice as you are vulnerable to SQLInjection. You should use parameterised query to run any script against your database. e.g.

using(OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connString))
{
conn.Open();
string query= "DELETE FROM Questions WHERE QID = @pID";
OleDbCommand comamnd = new OleDbCommand(query, conn);
comamnd.Parameters.Add("@pID",OleDbType.Integer).Value = j;
comamnd.CommandType = CommandType.Text;
command.ExecuteNonQuery();
conn.Close();
}

Altri suggerimenti

Best is to build up the OleDbCommand with Parameters.

 OleDbCommand oleDbCommand = new OleDbCommand("DELETE FROM Questions WHERE QID = @QID", acccon);
 oleDbCommand.Parameters.Add("@QID",OleDbType.Integer).Value = j;
 oleDbCommand.Prepare();
 oleDbCommand.ExecuteNonQuery();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top