简体   繁体   中英

c# using a binding source to add row to an sql table with incremental identity field

I have a program I created in Visual studio. The program is basically a place for everyone to store passwords for company and external accounts. I want to further this application by automatically creating the company accounts when I create a new user. I approached this by using the binding source. I can get the row into the database but it doesn't use the sql supplied auto increment. I will post the code but I am trying to figure out if I went about this the wrong way. I am not 100% familiar with how the connector and classes that visual studio create when you connect the solution to the database. I am not looking for code to help me do this I am looking for explanations and guidance. If responding with code please help me understand by explaining the code.

            DataSet.AccountsRow newdomainuserrow = DBDataSet.Accounts.NewAccountsRow();

            newdomainuserrow.USer = userIDTextBox.Text.ToString();
            newdomainuserrow.UserName = userIDTextBox.Text.ToString();

            System.DateTime moment = new DateTime();
            newdomainuserrow.Password = moment.Year;
            newdomainuserrow.AccountName = "Domain";
            drawingNumDBDataSet.Accounts.Rows.Add(newdomainuserrow);
            MessageBox.Show("User Saved");

            this.Validate();
            this.usersBindingSource.EndEdit();
            this.accountBindingSource.Endedit();
            this.tableAdapterManager.UpdateAll(this.DataSet);

All help is greatly appreciated.

Matt

I found a solution. The id field is not longer an identity autoincrement field. To increment the id field one by one programmatically like I need to I wrote a simply while statement to get all numbers that were not used. This works if there is a deleted row it will insert one where there is one missing. here is the code I used.

            Boolean gotnum;                
            gotnum = false;
            int idnum = 1;

            while  (gotnum != true)
            {
                DrawingNumDBDataSet.AccountsRow actrw = drawingNumDBDataSet.Accounts.FindById(idnum);
                idnum++;
                if (actrw==null)
                {

                    gotnum = true;
                    idnum--;
                }


            }

I then set the Id field = to idnum. This is probably not the best practice but it is the best I could come up with.

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