如何在c#中将更新参数添加到SQLDataSource

时间:2013-04-30 14:35:06

标签: c# gridview webforms sqldataadapter

参考我的问题,

How to get boundfield value, or am I totally wrong?

我正在尝试使用c#而不是ASP.NET将更新参数添加到SQLDataSource但是我收到错误,

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    int userID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["userID"].ToString());
    string userName = "";
    string city = "";
    string updateStatement = "Update myTable set userName=@userName, city=@city where userID=@userID";

    foreach (DictionaryEntry entry in e.NewValues)
    {
        if (entry.Key == "userName")
            userName = entry.Value.ToString();
        if (entry.Key == "city")
            city = entry.Value.ToString();
    }

    using (SqlDataSource ds = new SqlDataSource(ConnectionString(), updateStatement))
    {
       ds.UpdateParameters.Add("@userName");  
        ds.UpdateParameters.Add("@city");
       ds.UpdateParameters.Add("@UserId");
    }

    gvDetails.EditIndex = -1;
    BindData();
}

如何传递参数值:S

ds.UpdateParameters.Add("@userName");  
        ds.UpdateParameters.Add("@city");
       ds.UpdateParameters.Add("@UserId");

但我不知道正确的语法,有人可以指导我正确的方向吗

3 个答案:

答案 0 :(得分:3)

我认为您应该使用SqlCommand而不是SqlDataSource:

  using (SqlConnection connection = new SqlConnection(ConnectionString())
  using (SqlCommand cmd = new SqlCommand(updateStatement, connection)) {
    connection.Open();
    cmd.Parameters.Add(new SqlParameter("@Name", userName));
    cmd.Parameters.Add(new SqlParameter("@city", city));
    cmd.Parameters.Add(new SqlParameter("@UserId", userID));
    cmd.ExecuteNonQuery();
  }

答案 1 :(得分:1)

如果你想使用SQLDataSource,那么我相信语法是。

ds.UpdateParameters.Add("userName", "someDefaultValue");

否'@',您可以提供默认值。

答案 2 :(得分:0)

您无法向SqlDataSource添加参数。您可以添加SqlCommand。尝试类似的东西;

string updateStatement = "Update myTable set userName=@userName, city=@city where userID=@userID";

using (SqlDataSource ds = new SqlDataSource(ConnectionString(), updateStatement))
{       
        SqlCommand cmd = new SqlCommand(updateStatement);
        cmd.Parameters.Add("@userName");  
        cmd.Parameters.Add("@city");
        cmd.Parameters.Add("@UserId");
        cmd.Paramters["@City"].Value = city;
        cmd.Paramters["@userName"].Value = userName;
        cmd.Paramters["@UserId"].Value = userID;

        GridView1.DataSource = ds;
        GridView1.DataBind();
}