2010-12-14 71 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()代替。