开发者

Table auto increment does not work when data entered in running mode

开发者 https://www.devze.com 2023-01-19 01:06 出处:网络
i have written code that take开发者_开发知识库s data from text box and updates but as i have set in mdf file that ID will be auto incremented but this dose not happen.but if i enter data by right clic

i have written code that take开发者_开发知识库s data from text box and updates but as i have set in mdf file that ID will be auto incremented but this dose not happen.but if i enter data by right clicking "Show table data" in server explorer then there is auto increment here goes code

public partial class Form1 : Form
{
    System.Data.SqlClient.SqlConnection con;
    System.Data.SqlClient.SqlDataAdapter da;
    System.Data.SqlClient.SqlCommandBuilder cb;
    DataRow row;
    DataSet ds1;        
    public Form1()
    {
        InitializeComponent();
        con = new System.Data.SqlClient.SqlConnection();
        ds1 = new DataSet();

        con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
        try
        {
            con.Open();
            MessageBox.Show("Sucess Opening Database");
            string sql = "SELECT * From student";
            da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
            da.Fill(ds1,"students");
            dataGridView1.DataSource = ds1.Tables["students"];
            con.Close();
        }
        catch(Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }

    private void save_Click(object sender, EventArgs e)
    {
        cb = new System.Data.SqlClient.SqlCommandBuilder(da);
        row = ds1.Tables["students"].NewRow();
        row["Name"] = textBoxName.Text;
        row["Class"] = textBoxClass.Text;
        ds1.Tables["students"].Rows.Add(row);
        da.Update(ds1,"students");
        dataGridView1.DataSource = ds1.Tables["students"];
    }
}

Thanks in Advance


This was from a long time ago, but the answer is mentioned in a comment above from jgauffin.

If you set up an auto-increment column in a dataset and want it to auto increment your IDs for you, then pass in null when adding a new row.

0

精彩评论

暂无评论...
验证码 换一张
取 消