简体   繁体   English

将SQL查询的值返回到C#中的文本框

[英]Return value of sql query to textbox in C#

I want to access the last value in database column increment it by 1 and show on a textbox I used this code but nothing is displayed on text box what's wrong with this code? 我想访问数据库列中的最后一个值,将其递增1并显示在我使用此代码的文本框中,但文本框中什么都没有显示,此代码有什么问题?

SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No]  FROM addcustomer ", my);

int result = ((int)cmd.ExecuteScalar());
textBox1.Text = result.ToString();
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar()) + 1;
textBox1.Text = result.ToString();

You have wrongly placed bracket. 您放置了错误的支架。 Change this 改变这个

SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No]  FROM addcustomer ", my);

into that 进入那个

SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);

Looks like you're missing a bracket: 好像您缺少括号:

SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No]  FROM addcustomer ", my);

should be 应该

SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer", my);
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);

you can change the sql statement as below 您可以如下更改sql语句

SELECT MAX(Account_No) + 1 FROM addcustomer

or increment after selecting value by code 或按代码选择值后递增

SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar()) +1;

Final Code would be : 最终代码为:

try
{
    using (SqlConnection con = new SqlConnection(connectionString))
    using (SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) + 1 FROM addcustomer", con))
    {
        con.Open();
        int result = (int)cmd.ExecuteScalar();
        textBox1.Text = result.ToString();
    }
}
catch (SqlException ex)
{
    MessageBox.Show(ex.ToString()); // do you get any Exception here?
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM