列'值'不属于表

时间:2015-11-18 14:59:26

标签: c#

我已经在我的数据库的tblV表中的列名Value下存储了一些数字数据。我想将该列中的数据值放入textbox1。 但是,只要我点击按钮,它就会显示Column 'Value' does not belong to table错误,即使表格中有列Value也是如此。是什么导致了这个问题?

第一个是类,第二个是按钮点击事件的代码。

 public DataTable GetMaxno(decimal Licenseno)
    {
        SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;");
        string sql = "select Max(Value) from tblv where Licenseno=@licenseno";
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.AddWithValue("@Licenseno",Licenseno );
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable DT = new DataTable();
        da.Fill(DT);
        return DT;
    }



 tryv tv = new tryv();
    private void button1_Click(object sender, EventArgs e)
    {
        DataTable dt = tv.GetMaxno(Convert.ToDecimal(textBox2.Text));
        if (dt.Rows.Count > 0)
        {
            textBox1.Text= dt.Rows[0]["Value"].ToString();
        }
    }

2 个答案:

答案 0 :(得分:4)

原因可能是您的查询未返回任何别名Value。您可以使用select Max(Value) as Value来解决这个问题,但不要使用ExecuteScalar,而是使用using statement,这正是您想要的。它返回第一行的第一列。

还有一些事情;

public int GetMaxno(decimal Licenseno)
{
     using(var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;")
     using(var cmd = con.CreateCommand())
     {
        cmd.CommandText = "select Max(Value) from tblv where Licenseno = @licenseno";
        cmd.Parameters.Add("@licenseno", SqlDbType.Decimal).Value = Licenseno;
        con.Open();
        return (int)cmd.ExecuteScalar();
     }
}

然后你可以做;

textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();

答案 1 :(得分:1)

string sql = "select Max(Value) as Value from tblv where Licenseno=@licenseno";