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


/ Published in: C#
Save to your folder(s)

Bind the DropDownList like normal (set DataSourceID, DataTextField, DataValueField), and the SelectedValue field. AutoPostBack should be enabled. In the OnSelectedIndexChanged:


Copy this code and paste it in your HTML
  1. protected void DropDownSelectedIndexChanged(object sender, EventArgs e)
  2. {
  3. //http://programming.top54u.com/post/GridView-DropDownList-Update-SelectedValue-All-At-Once.aspx
  4. //http://www.codeproject.com/KB/webservices/db_values_dropdownlist.aspx
  5.  
  6. DropDownList d = sender as DropDownList;
  7. if (d == null) return;
  8.  
  9. //grab row that contains the drop down list
  10. GridViewRow row = (GridViewRow)d.NamingContainer;
  11.  
  12. //pull data needed from the row (in this case we want the ID for the row)
  13. object ID = gridEntries.DataKeys[row.RowIndex].Values["tableID"];
  14.  
  15.  
  16. SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
  17. conn.Open();
  18.  
  19. SqlCommand c = new SqlCommand("UPDATE table SET value = @v WHERE tableID = @id", conn);
  20.  
  21. SqlParameter p = c.Parameters.Add("@id", SqlDbType.Int);
  22. p.Value = Convert.ToInt32(ID);
  23.  
  24. p = c.Parameters.Add("@v", SqlDbType.Int);
  25. p.Value = Convert.ToInt32(d.SelectedValue);
  26.  
  27. c.ExecuteNonQuery();
  28.  
  29. //databind the gridview to reflect new data.
  30. gridEntries.DataBind();
  31. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.