从
数据库中填充特定下拉列表值的问题,我想向用户显示数据库表中的所有当前数据,让他们能够进行更改,但我无法显示用户之前选择的特定下拉列表。我使用 linq数据源显示所有下拉列表值。
public partial class Update : System.Web.UI.Page
{
string cs = Global.CS;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) // only during initial load
{
string id = Request.QueryString["Item_ID"] ?? "";
string sql = "Select * FROM MenuItem WHERE Item_ID = @id";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@Id", id);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
if ((string)dr["Category"] == "Breakfast" || (string)dr["Category"] == "Lunch" || (string)dr["Category"] == "Dinner")
{
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
//foreach (var checking in db.Sets)
//{
// string setID = checking.Set_ID.ToString();
// if (setID == (string)dr["Item_ID"])
// {
// ddlAlacarte.DataSourceID = "ldsAlacarte";
// **ddlAlacarte.DataTextField = (string)dr["ItemDesc"].ToString();
// ddlAlacarte.DataValueField = (string)dr["Item_ID"].ToString();**
// }
//}
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
}
}
else
{
Response.Redirect("MenuAdmin.aspx");
}
DataBind();
dr.Close();
con.Close();
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategory.SelectedItem.Text == "Breakfast" || ddlCategory.SelectedItem.Text == "Lunch" || ddlCategory.SelectedItem.Text == "Dinner")
{
ddlAlacarte.Enabled = true;
ddlBeverage.Enabled = true;
ddlSide.Enabled = true;
DataBind();
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
}
}
}
您需要在
读取值时在下拉列表中添加项目。
在使用 SqlDataReader 读取值时添加以下代码。
while(dr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = dr["Category"].ToString();
listItem.Value = dr["Category"].ToString();
categoryDropDownList.Items.Add(listItem);
}
我会使用这样的东西
dropDownList.Items.Add(
new ListItem(){ Text = dr["Breakfast"], Value = dr["Breakfast"] }
);
并循环访问,填充下拉列表。这就是你想要的吗?