2013-09-21 34 views
0

轉換失敗我有3個文本框並添加按鈕。當按鈕被點擊時,它應該從文本框向數據庫插入信息。問題是,當它被點擊,我有以下錯誤:Conversion failed when converting the varchar value '@id' to data type int. 這裏是添加按鈕onclick事件:將varchar值'@id'轉換爲數據類型int

SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True"); 
      SqlCommand cmd = new SqlCommand("addData", conn); 
      conn.Open(); 
      cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = Convert.ToInt32(txtID.Text); 
      cmd.Parameters.Add("@FName", System.Data.SqlDbType.VarChar).Value = txtFName.Text; 
      cmd.Parameters.Add("@LName", System.Data.SqlDbType.VarChar).Value = txtLName.Text; 
      cmd.CommandType = CommandType.StoredProcedure; 
      SqlDataReader rd = cmd.ExecuteReader(); 
      GridView1.DataSource = rd; 
      GridView1.DataBind(); 

而且我有一個存儲過程,而增加了數據,我想我會在這裏犯了一個錯誤:

USE ['Name'] 
GO 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER procedure [dbo].[addData] 
@id int, 
@FName varchar(30), 
@LName varchar(30) 
as 
begin 
Insert into Customer(ID, FName, LName) 
Values('@id', '@FName', '@LName') 
end 

請幫我找到我的錯誤。

回答

4

您需要更換

Values('@id', '@FName', '@LName') 

Values(@id, @FName, @LName) 
+1

非常感謝,這解決了我的問題 – Eugene

1

您缺少@登錄您的參數。

SqlConnection conn = new SqlConnection("Data Source="Name";Initial Catalog="Name";Integrated Security=True"); 
      SqlCommand cmd = new SqlCommand("addData", conn); 
      conn.Open(); 
      cmd.Parameters.Add("@id", System.Data.SqlDbType.Int) 
          .Value = Convert.ToInt32(txtID.Text); 
      cmd.Parameters.Add("@FName",System.Data.SqlDbType.VarChar) 
          .Value = txtFName.Text; 
      cmd.Parameters.Add("@LName", System.Data.SqlDbType.VarChar) 
          .Value = txtLName.Text; 
      cmd.CommandType = CommandType.StoredProcedure; 
      SqlDataReader rd = cmd.ExecuteReader(); 
      GridView1.DataSource = rd; 
      GridView1.DataBind(); 
      conn.Close()//don't forget to close conn 
+0

剛剛加入,仍然有同樣的錯誤 – Eugene

相關問題