Return to Snippet

Revision: 14367
at June 1, 2009 20:39 by jink


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

Initial URL
http://www.codeproject.com/KB/webservices/db_values_dropdownlist.aspx

Initial Description
Bind the DropDownList like normal (set DataSourceID, DataTextField, DataValueField), and <%BIND%> the SelectedValue field.  AutoPostBack should be enabled.  In the OnSelectedIndexChanged:

Initial Title
ASP.net: Update SQL from a DropDownList dynamically created in a GridView.

Initial Tags
sql, aspnet, update

Initial Language
C#