2010-12-14 86 views
0

我不知道爲什麼每次我執行更新我的記錄,我更新的查詢不增加ID從0到1,總是需要0 ..我不知道「知道我如何增加我的ID設置爲1,到目前爲止..請解釋一下..:/ ..我的代碼是:更新記錄c中的問題#

private void btnUpdate_Click(object sender, EventArgs e) 
      { 
       int CustomerID =0; 
       SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS; 
       Initial Catalog=Gym;Integrated Security=True"); 
       SqlCommand cmd = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn); 
       SqlDataAdapter da = new SqlDataAdapter(cmd); 
       DataTable dt = new DataTable(); 
       da.Fill(dt); 
       BindGridView(); 
      } 


private void BindGridView() 
     { 
      SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS;Initial Catalog=Gym;Integrated Security=True"); 
      SqlCommand cmd = new SqlCommand("Select * from Customer", cn); 
      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      DataTable dt = new DataTable(); 
      da.Fill(dt); 
      dgView_CustomerInfo.DataSource = dt.DefaultView; 
     } 
+1

您知道UPDATE更新*現有*記錄。如果ID是一個IDENTITY列,它只會在您插入記錄時增加...... – 2010-12-14 08:48:06

+4

首先,也是最重要的一點,請閱讀SQL注入和參數化查詢。其次,你在那裏做的很腥......你將一個空的DataTable綁定到DataGridView ......兩次。這似乎很奇怪。第三,如果你永遠不增加它,爲什麼要增加ID?據我所知,你的意思是表格的Auto-Id,但是'Update'並不影響它。 – Bobby 2010-12-14 08:49:50

+0

ohh ..我想更新現有的記錄..我已初始化int CustomerID = 0,但..我沒有得到,當用戶點擊存在於gridview中的現有記錄時,如何更改id .. – 2010-12-14 08:55:55

回答

0

你真的需要閱讀一本關於.net編程的書。您的代碼是完全毛刺......

讓你開始...

 // put the connection string into the app.config 
     using (SqlConnection cn = new SqlConnection(@"Data Source=COMPAQ-PC-PC\SQLEXPRESS; Initial Catalog=Gym;Integrated Security=True")) 
     { 
      int result = new SqlCommand("Update Customer set Customer_Name = '" + tbName.Text + "',Cell_Number = '" + tbContactNumber.Text + "',Customer_Address = '" + tbAddress.Text + "' where CustomerID = " + CustomerID, cn).ExecuteNonQuery(); 
      // eval result to see wether there was realy an updated record... 
     } 

在一個SqlConnection使用using()聲明。這樣處理對象就被處理了。實際上將它用於所有可丟棄的物體。

嘗試使用app.config/web.config作爲連接字符串。

將轉到sql server的所有用戶輸入轉義以防止sql注入。 http://de.wikipedia.org/wiki/SQL-Injection

+0

你能把這本書給我嗎? – 2010-12-14 09:05:59

+0

我已將您的代碼替換爲我的代碼,並且我不知道爲什麼當我點擊更新按鈕時它什麼都不做。 – 2010-12-14 09:13:20

+0

如果在更新事件中設置了斷點,它實際上是否調用更新?並且由於您正在更新,所以ID不會增加... – 2010-12-14 09:21:42

0

您正在使用‘更新客戶’SQL子句。 這意味着你要更新EXISTING記錄,而不是插入NEW記錄。

該ID僅對新記錄遞增,但對現有記錄不遞增。 另外,請確保您的ID列已正確配置。 它應該具有IDENTITY(1,1)子句像下面的例子中:

CREATE TABLE [dbo].[td_Component](
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [Url] [nvarchar](250) NOT NULL, 
    [Caption] [nvarchar](50) NOT NULL, 
    [Description] [varchar](4000) NULL, 
+0

我已經完成了那個..:/ – 2010-12-14 08:56:11

2

您需要使用Command.ExecuteNonQuery()代替。