简体   繁体   中英

winforms C# using sql server 2008

private void fillcode()
{
    try
    {
        SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
        con.Open();
        string s = "select max(CustomerId) as Id from CustomerDetails";
        SqlCommand cmd = new SqlCommand(s, con);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        int i = Convert.ToInt16(dr["Id"].ToString());
        sid.Text = (i + 1).ToString();
        con.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

I am using this code, but there is a problem if there is no data in my table it will not accept. So I want to use if no data is present it should take CustomerId as 1

It will be NULL of there are no rows so you can:

"select isnull(max(CustomerId), 1) as Id from CustomerDetails"

You should also look at ExecuteScalar which is designed for a singe result.

Try like this

private void fillcode()
{
    try
    {
        SqlConnection con = new SqlConnection("Data Source=ANISH;Initial Catalog=HM;Integrated Security=True");
        con.Open();
        string s = "select max(CustomerId) as Id from CustomerDetails";
        SqlCommand cmd = new SqlCommand(s, con);
        SqlDataReader dr = cmd.ExecuteReader();
        if(dr.Read())
        {
            int i = Convert.ToInt16(dr["Id"].ToString());
            sid.Text = (i + 1).ToString();
        }
        else
        {
            sid.Text = "1"
        } 
        con.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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