我已经在我的数据库的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();
}
}
答案 0 :(得分:4)
原因可能是您的查询未返回任何别名Value
。您可以使用select Max(Value) as Value
来解决这个问题,但不要使用ExecuteScalar
,而是使用using
statement,这正是您想要的。它返回第一行的第一列。
还有一些事情;
AddWithValue
。 https://github.com/ckan/ckanapi。使用Add
方法重载来指定参数类型及其大小。
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";