I have a ugly code that can’t be reused. I have many similar queries. I want to rewrite it with SqlParameterCollectionExtensions or other better ways. But I don’t know about SqlParameterCollectionExtensions at all.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Problem_DE SET ProbDesc = @ProbDesc, field_1 = @field_1, field_2 = @field_2, field_3 = @field_3, field_4 = @field_4, field_5 = @field_5, field_6 = @field_6, field_7 = @field_7 WHERE (ProbId = @ProbId)";
if (e.NewValues["ProbDesc"] == null)
cmd.Parameters.AddWithValue("@ProbDesc", DBNull.Value);
else
cmd.Parameters.AddWithValue("@ProbDesc", e.NewValues["ProbDesc"]);
if (e.NewValues["field_1"] == null)
cmd.Parameters.AddWithValue("@field_1", DBNull.Value);
else
cmd.Parameters.AddWithValue("@field_1", e.NewValues["field_1"]);
if (e.NewValues["field_2"] == null)
cmd.Parameters.AddWithValue("@field_2", DBNull.Value);
else
cmd.Parameters.AddWithValue("@field_2", e.NewValues["field_2"]);
if (e.NewValues["field_3"] == null)
cmd.Parameters.AddWithValue("@field_3", DBNull.Value);
else
cmd.Parameters.AddWithValue("@field_3", e.NewValues["field_3"]);
if (e.NewValues["field_4"] == null)
cmd.Parameters.AddWithValue("@field_4", DBNull.Value);
else
cmd.Parameters.AddWithValue("@field_4", e.NewValues["field_4"]);
\\ blah blah
cmd.ExecuteNonQuery();
con.Close();
}
The sql parameters come from e or textbox etc.
Thanks.
Maybe something like this? I assume the problem is that you have a variable number of values, depending on the problem table?
An example to call this code would be:
The example code above is obviously just a demonstration of how to make an array of objects stored from page control values and doesn’t include any data validation that you will need to implement in production code.
If you won’t know how big the object[] array needs to be at runtime, you can change it to be a generic List of objects and add the items dynamically.