2013-06-20 34 views
-1

即时通讯从一个webform更新我的数据库的问题。我使用了一系列由数据源填充的文本框和下拉列表,但出于某种原因,我无法更新它们。使用asp.net更新sql server数据库c#

基本上,行的主键传递到下一个页面,其中文本框,下拉列表中填充了该行的数据。

这里是我到目前为止已经试过

//Update the record with new information entered into controls 
    protected void UpdateBut_Click(object sender, EventArgs e) 
    { 

     using (SqlConnection conn = new SqlConnection("Data Source=stephenp\\sqlexpress;Initial Catalog=Asset management System DB;Integrated Security=True")) 
     { 
      string sql = "UPDATE Peripherals SET [email protected], [email protected], [email protected], " + 
       "Company = @Company, [email protected], [email protected], [email protected], [email protected], " + 
       "[email protected], LastModifiedDate = @LastMD, [email protected] WHERE (PeripheralTagNumber = @PeripheralTagNumber)"; 


      //try 
      //{ 
      using (SqlCommand cmd = new SqlCommand(sql, conn)) 
      { 
       cmd.Parameters.AddWithValue("@PeripheralType", TypeDDL.Text.Trim()); 
       cmd.Parameters.AddWithValue("@Model", ModelTB.Text.Trim()); 
       cmd.Parameters.AddWithValue("@SerialNum", SerialNumTB.Text.Trim()); 
       cmd.Parameters.AddWithValue("@Company", CompanyDDL.Text.Trim()); 
       cmd.Parameters.AddWithValue("@Department", DepartmentDDL.Text.Trim()); 
       cmd.Parameters.AddWithValue("@Status", StatusDDL.Text.Trim()); 
       cmd.Parameters.AddWithValue("@Warranty", DateTime.Parse(WarrantyTB.Text.Trim()).ToShortDateString()); 
       cmd.Parameters.AddWithValue("@CapexNum", CapexNumTB.Text.Trim()); 
       cmd.Parameters.AddWithValue("@IPAddress", IPAddressTB.Text.Trim()); 
       cmd.Parameters.AddWithValue("@LastMD", DateTime.Now.Date.ToShortDateString()); 
       cmd.Parameters.AddWithValue("@LastMB", Session["username"].ToString()); 
       cmd.Parameters.AddWithValue("@PeripheralTagNumber", ID); 

       conn.Open(); 
       cmd.ExecuteNonQuery(); 
       conn.Close(); 
      } 
      //} 
      //catch (SqlException ex) { } 
     } 

     this.getData(); 
    } 

感谢

+0

你得到错误? –

+0

你的爱是什么? –

+0

那么,你的代码问题是什么?例外?错误讯息?不要更新任何内容?请更具体的 – Steve

回答

0

使用AddWithValue可能会导致一些细微的错误。例如,如果您的列LastModifiedDate属于日期时间类型,您应该传递一个DateTime值作为AddWithValue中的第二个参数,而不是字符串。 同为WarrantyDate

你可以试着改变这些线

cmd.Parameters.AddWithValue("@LastMD", DateTime.Now.Date); 
cmd.Parameters.AddWithValue("@Warranty", DateTime.Parse(WarrantyTB.Text.Trim())); 
0

你应该使用块的try/catch当你构建你的SqlCommand,当你执行你的查询。

如果数据库中没有更新,您的命令可能有问题。

+0

问题解决了!我遗憾地忘记在我的主要方法中使用if(!IsPostBack),这意味着当我调用更新数据库时它仍在更新,但值正在用数据库中的当前值进行更新,即值正在更新完全相同的值。如果(!IsPostBack)通过允许使用输入到文本框/下拉列表中的新值更新来解决问题,则添加。 –

相关问题