How to add update parameter to SQLDataSource in c#

时光总嘲笑我的痴心妄想 提交于 2019-12-13 19:21:21

问题


In reference to my question,

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

I am trying to add update parameter to a SQLDataSource using c# instead of ASP.NET but I am getting error,

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();
}

How can I pass values of parameters :S

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

But I don't know the right syntax, can someone direct me in right direction please


回答1:


I think you should use an SqlCommand instead of 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();
  }



回答2:


if you want to use SQLDataSource, then I believe the syntax is.

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

No '@' and you can supply the default value.




回答3:


You can't add parameters to SqlDataSource. You can add SqlCommand instead. Try something similar like this;

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();
}


来源:https://stackoverflow.com/questions/16302494/how-to-add-update-parameter-to-sqldatasource-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!