[英]c# using a binding source to add row to an sql table with incremental identity field
我有一個在Visual Studio中創建的程序。 該程序基本上是每個人都可以存儲公司和外部帳戶密碼的地方。 我想通過在創建新用戶時自動創建公司帳戶來擴展此應用程序。 我通過使用綁定源來解決這個問題。 我可以將行放入數據庫,但不使用sql提供的自動增量。 我將發布代碼,但是我試圖弄清楚我是否以錯誤的方式進行操作。 當您將解決方案連接到數據庫時,我不是100%熟悉Visual Studio如何創建連接器和類。 我不是在尋找幫助我做到這一點的代碼,而是在尋找解釋和指導。 如果回復代碼,請通過解釋代碼來幫助我理解。
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);
非常感謝所有幫助。
馬特
我找到了解決方案。 id字段不再是身份自動遞增字段。 要像我需要的那樣以編程方式逐一遞增id字段,我編寫了一個while語句來獲取所有未使用的數字。 如果有被刪除的行,這將起作用,它將在缺少的行中插入一個。 這是我使用的代碼。
Boolean gotnum;
gotnum = false;
int idnum = 1;
while (gotnum != true)
{
DrawingNumDBDataSet.AccountsRow actrw = drawingNumDBDataSet.Accounts.FindById(idnum);
idnum++;
if (actrw==null)
{
gotnum = true;
idnum--;
}
}
然后,我將Id字段=設置為idnum。 這可能不是最佳做法,但我可以提出的最佳做法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.