Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
pls some one tell that how to get autoincreamented id in asp.net c#, i write the code but it throws error

Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)


and code is
C#
public void gen1()
{
    con.Open();
    int a = 0;
    SqlCommand com = new SqlCommand("select max(id) from Category", con);
    a = com.ExecuteScalar();
    TextBox4.Text = Convert.ToString(a);
    con.Close();
}




pls help me to correct...
Posted
Updated 30-Oct-12 20:49pm
v2

Hi Rani,
    Try replacing
C#
a = com.ExecuteScalar();

with
C#
a = Conver.ToInt32(com.ExecuteScalar());

Check SqlCommand.ExecuteScalar Method[^] which returns object. You need to cast that object to a specified type.

It'll work out.
    --Amit
 
Share this answer
 
v2
Comments
bbirajdar 31-Oct-12 3:00am    
This should work .. +5
_Amy 31-Oct-12 3:01am    
Thanks! :)
Try This,
C#
public void Autogenrate()
{
    int r;
    try
    {
      con = new SqlConnection("data source=XYZ; user id=ABC; password=***; initial catalog=Detail");
   con.Open();
        SqlCommand cmd = new SqlCommand("Select max(id) from empp1", con);
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.Read())
        {

            string d = dr[0].ToString();
            if (d == "")
            {

                id.Text = "1001";//set the value in textbox which name is id

            }
            else
            {

                r = Convert.ToInt32(dr[0].ToString());
                r = r + 1;
                id.Text = r.ToString();
            }
        }
        con.Close();
        con.Open();

      cmd.CommandText = "insert empp1 values('" + id.Text + "','" +   txtName.Text + "','" + txtCity.Text + "')";

        cmd.ExecuteNonQuery();
    }

    catch (Exception ex)
    {
        Response.Write("<script>alert("+ex.Message+")</script>");
    }
    finally
    {
        con.Close();
    }
}
 
Share this answer
 
v2
Comments
Member 12896830 20-Dec-16 2:08am    
what is this id.Text = "1001";
can you please explain
you can increment the id in table ,


click here
 
Share this answer
 
 
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