问题
- i am developing my app on visual studio 2008
- i have 4 tables
- i have a dropdownlist (displays product_category_names)
- i need to do an insert statement
i have the following code:
Dim sql2 As String = "INSERT INTO Product (product_category_id, product_name, product_title, product_desc, product_author, product_author_age, product_author_desc, product_other_detail, product_dimension1, product_dimension2, product_price, product_institution, product_status, product_delivery_time) VALUES (@product_category_id, @product_name, @product_title, @product_desc, @product_author, @product_author_age, @product_author_desc, @product_other_detail, @product_dimension1, @product_dimension2, @product_price, @product_institution, @product_status, @product_delivery_time)"
cmd.Parameters.Add(New SqlParameter("@product_name", (txtProductName2.Text))) cmd.Parameters.Add(New SqlParameter("@product_title", (txtProductTitle2.Text)))
Question is, how may I insert 'product_category_id' (an Integer) into the table 'Product', when the dropdownlist displays 'product_category_names' instead of 'product_category_id'?
Can someone show me the light? Thanks.
回答1:
Assuming you are binding your dropdownlist on the page load event and using the product_Catogry table then The easiest way would be to bind product_category_ID to the value property of the dropdownlist. This way you can programatically access the ID while the user sees the name.
DropDownList.DataSource = [your product table]
DropDownList.DataTextField = "Proudct_Category_Name"
DropDownList.DataValueField = "Product_category_ID"
If this is not an option for whatever reason then the below SQL will work in your current command, just make sure you add @Product_Category_Name as a parameter to the SqlCommand instead of @product_Category_Name.
INSERT INTO Product
( product_category_id,
product_name,
product_title,
product_desc,
product_author,
product_author_age,
product_author_desc,
product_other_detail,
product_dimension1,
product_dimension2,
product_price,
product_institution,
product_status,
product_delivery_time
)
SELECT product_category_id,
@product_name,
@product_title,
@product_desc,
@product_author,
@product_author_age,
@product_author_desc,
@product_other_detail,
@product_dimension1,
@product_dimension2,
@product_price,
@product_institution,
@product_status,
@product_delivery_time
FROM product_category
WHERE product_category_Name = @Product_Category_Name
Or you could simply add this to the start of your current SQL:
DECLARE @Product_Category_ID INT
SELECT @Product_Category_ID = Product_Category_ID
FROM Product_Category
WHERE Product_Category_Name = @Product_Category_Name
And continue with the insert ... values ().
来源:https://stackoverflow.com/questions/9043348/insert-integer-when-dropdownlist-displays-strings-as-datavaluefield