Reputation: 1
I have stored some number data under column name Value in the tblV
table of my database. I want to put the data from that column Value into textbox1
.
But whenever I click the button it shows Column 'Value' does not belong to table
error even though there is column Value
in the table. What is causing this problem?
The first one is class and second one is the code on button click event.
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();
}
}
Upvotes: 0
Views: 657
Reputation: 98750
Reason might be that your query does not return any aliases as Value
. You can solve this with select Max(Value) as Value
but instead of that, use ExecuteScalar
instead which is exactly what you want. It returns first column of the first row.
A few things more;
using
statement to dispose your connection and command.AddWithValue
. It may generate unexpected and surprising result sometimes. Use Add
method overloads to specify your parameter type and it's size.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();
}
}
Then you can do;
textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();
Upvotes: 4
Reputation: 3744
try
string sql = "select Max(Value) as Value from tblv where Licenseno=@licenseno";
Upvotes: 1