Thursday, February 18, 2010

Update SQL from a DropDownList dynamically created in a GridView

protected void DropDownSelectedIndexChanged(object sender, EventArgs e)
{
//http://programming.top54u.com/post/GridView-DropDownList-Update-SelectedValue-All-At-Once.aspx
//http://www.codeproject.com/KB/webservices/db_values_dropdownlist.aspx

DropDownList d = sender as DropDownList;
if (d == null) return;

//grab row that contains the drop down list
GridViewRow row = (GridViewRow)d.NamingContainer;

//pull data needed from the row (in this case we want the ID for the row)
object ID = gridEntries.DataKeys[row.RowIndex].Values["tableID"];

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
conn.Open();

SqlCommand c = new SqlCommand("UPDATE table SET value = @v WHERE tableID = @id", conn);

SqlParameter p = c.Parameters.Add("@id", SqlDbType.Int);
p.Value = Convert.ToInt32(ID);
p = c.Parameters.Add("@v", SqlDbType.Int);
p.Value = Convert.ToInt32(d.SelectedValue);

c.ExecuteNonQuery();

//databind the gridview to reflect new data.
gridEntries.DataBind();
}

No comments: