我創建的表稱爲
Department
2列Department ID
這是自動遞增和Department Name
如何使用的SqlCommand和DataAdapter以操縱SQL Server和C#我爲了通過部門走路創建
Navigate_Department()
行System.Data.SqlClient.SqlConnection con; DataSet Dep_ds; System.Data.SqlClient.SqlDataAdapter Dep_da; int Dep_MaxRows = 0; int Dep_inc = 0; private void ILS_Load(object sender, EventArgs e) { con = new System.Data.SqlClient.SqlConnection(); con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\ILS_DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; con.Open(); Dep_ds = new DataSet(); string sql2 = "select * from Department order by DepartmentID"; Dep_da = new System.Data.SqlClient.SqlDataAdapter(sql2, con); Dep_da.Fill(Dep_ds, "Department"); Navigate_Department(); Dep_MaxRows = Dep_ds.Tables["Department"].Rows.Count; } private void Navigate_Department() { DataRow dRow = Dep_ds.Tables["Department"].Rows[Dep_inc]; Dep_ID.Text =dRow.ItemArray.GetValue(0).ToString(); Dep_Name.Text = dRow.ItemArray.GetValue(1).ToString(); } private void Move_Next_Click(object sender, EventArgs e) { if (Dep_inc != Dep_MaxRows-1) { Dep_inc++; Navigate_Department(); } else { MessageBox.Show("No More Records"); } } private void Move_back_Click(object sender, EventArgs e) { if (Dep_inc > 0) { Dep_inc--; Navigate_Department(); } else { MessageBox.Show("First Record"); } } private void Dep_Clear_Click(object sender, EventArgs e) { Dep_ID.Clear(); Dep_Name.Clear(); } private void Dep_Add_Click(object sender, EventArgs e) { try { SqlCommand insCmd = new SqlCommand("insert into dbo.Department (DepartmentName) values ('" + Dep_Name.Text + "')", con); Dep_da.InsertCommand = insCmd; Dep_MaxRows = Dep_MaxRows + 1; Dep_inc = Dep_MaxRows - 1; Dep_Max.Text = Dep_MaxRows.ToString(); Dep_Current.Text = (Dep_MaxRows).ToString(); } catch (Exception exceptionObject) { MessageBox.Show(exceptionObject.Message); }
的問題是:
當我點擊清除按鈕後,我將部門名稱插入到Dep_Name
文本框中,然後單擊添加按鈕。我插入的名稱未保存在數據庫中,如果我單擊後退,然後再移動以查看插入的內容,我在Navigate_Department()
方法中得到一個Index out of range
例外。
那麼我犯了什麼錯誤?
參數化您的SQL查詢。不要將文本框值附加到SQL字符串中。 –