Click here to Skip to main content
15,917,174 members
Please Sign up or sign in to vote.
3.86/5 (3 votes)
Hi,
I have a text box named txtItemID. An Sql data base table named Item is used. It has the column named ItemID, which is created by using max(ItemID)+1 value. My requirement is whenever the page load occurs(run my page in asp .net), the max(ItemID)+1 value should be shown in the text box txtItemID. I have done these codes but it doesn't works :

C#
private void BindItemID()
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("Select ItemID from Item", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        txtItemID.Text = dt.ToString();
        txtCode.DataBind();     
        
    }
Posted

Will return the last ItemID from table 'Item'
SQL
SELECT IDENT_CURRENT('Item')


Will populate the value to textbox
C#
txtItemID.Text = Convert.ToString(dt.Rows[0]["ItemID"]);
 
Share this answer
 
v2
Hi,
Use like

C#
private void BindItemID()
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString);
    string sItemID = string.Empty;
    try
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("Select max(ItemID)+1 from Item", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        sItemID = Convert.ToString(cmd.ExecuteScalar());
        txtItemID.Text = sItemID.ToString().Trim();
    }
    catch (Exception ex)
    {
    }
    finally
    {
        con.Close();
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900