I am trying to insert records into SQL Server 2012 using C#.
I've done it in this way, but the problem is the insert record statement does not add the record at the end of the table.
It was working correctly, but sometimes (each time is different) it is inserting in the middle of the records and sometimes work correctly. it is not clear for me why this is happening.Figure
Any soultion ?
public partial class AddDoc : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source=.\BAKRSQL; Database=Diseases Prediction Sys;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd;
string com = "select top 1 DId From Doctor ORDER BY DId Desc;";
con.Open();
cmd = new SqlCommand(com, con);
object count = cmd.ExecuteScalar();
if (count != null)
{
int i = Convert.ToInt32(count);
i++;
TextBox1.Text = i.ToString();
}
else
{
TextBox1.Text = "101";
}
con.Close();
}
protected void Button2_Click(object sender, EventArgs)
{ SqlConnection con = new SqlConnection();
con.ConnectionString =@"Data Source=.\BAKRSQL; Database=Diseases Prediction Sys;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand("insert into Doctor(DId,Name,Address,Mobile) values (@DId,@Name,@Address,@Mobile);", con);
cmd.Parameters.AddWithValue("@DId", TextBox1.Text);
cmd.Parameters.AddWithValue("@Name", TextBox2.Text);
cmd.Parameters.AddWithValue("@Address", TextBox3.Text);
cmd.Parameters.AddWithValue("@Mobile", TextBox4.Text);
cmd.ExecuteReader();
con.Close();
con.Open();
}
}