无法将变量与数据表值进行比较 - C#

时间:2017-06-30 09:04:35

标签: c# jquery datatable

我正在将变量与数据库中保存在数据表中的某些值进行比较。

但是,我无法从数据表中的行中获取值以与变量进行比较。

我的代码如下:

private void tabelacategorias_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    var senderGrid = (DataGridView)sender;

    if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
    {
        var idtabelacat = tabelacategorias.Rows[e.RowIndex].Cells["id_categoria"].Value;

        MySqlConnection mConn = new MySqlConnection("Persist Security Info=False;server = localhost; port=3307; database = startselling; user = root; password = usbw;");
        MySqlCommand command_getcats = new MySqlCommand("SELECT c.id_categoria FROM produtos p RIGHT JOIN categorias c ON p.id_categoria = c.id_categoria WHERE p.id_categoria IS NULL", mConn);
        DataTable dtcats = new DataTable();
        MySqlDataAdapter dacats = new MySqlDataAdapter(command_getcats);
        mConn.Open();
        dacats.Fill(dtcats);
        mConn.Close();
        numcats = dtcats.Rows.Count;
        int v = 0;
        foreach (DataRow row in dtcats.Rows)
        {
            var idcats = row["c.id_categoria"];    

            if (idcats == idtabelacat)
            {
                MySqlCommand command_delcat = new MySqlCommand("DELETE FROM categorias where id_categoria ='" + idtabelacat + "'");
                command_delcat.Connection = mConn;
                mConn.Open();
                MySqlDataReader reader = command_delcat.ExecuteReader();
                mConn.Close();
                MessageBox.Show("You deleted the category!");
                v = 1;
                update_tabelas();                        
                break;

            }
        }
        if (v == 1)
        {
            MessageBox.Show("You aren't able to delete this category!");
        }
    }
}

基本上变量 idcats 什么都不返回。我希望它从数据表中返回一个值。

如果你能帮助我,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

  1. 从查询返回的列将没有表别名,因此请使用: 行[ “id_categoria”]

  2. SELECT c.id_categoria FROM produtos p RIGHT JOIN categorias c ON p.id_categoria = c.id_categoria WHERE p.id_categoria IS NULL表示 p.id_categoria IS NULL ,因此该变量为空是合乎逻辑的。

  3. 更改查询中的WHERE子句,正确的值将显示在变量中。

    希望它有所帮助。