[英]How to populate a GridView drop-down list choices from SQL?
這是我希望我的網格視圖執行的操作。
我的SQL表Pharmacy_Data包含Item_Name和Item_Code
從Pharmacy_Data表填充Item_Code。 當我從下拉列表中選擇項目名稱時,它應該在字段中填寫項目代碼。
我該怎么辦?
1.將Item name dropdownlist的Autopostback設置為true,並在dropdownlist change事件內寫入用於獲取數據(Item code)的代碼並填寫Item code
請參閱下面的鏈接 ..這可能會幫助您。 在鏈接的示例中,他們使用直接值來填充使用列表的下拉列表,而不是針對您的案例使用數據庫。
我通過向我的GridView添加OnRowDataBound函數解決了此問題。
OnRowDataBound =“ Grid_ItemList_RowDataBound”
protected void Grid_ItemList_RowDataBound(object sender, GridViewRowEventArgs e)
{
Connection con = new Connection();
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlnames = (e.Row.FindControl("ddlnames") as DropDownList);
ddlnames.DataSource = con.GetData("Select Item_Code,Item_Name from mytable");
//TextValue Pairs of DropDown list
ddlnames.DataTextField = "Item_Name";
ddlnames.DataValueField = "Item_Code";
ddlnames.DataBind();
//Add Default Item in the DropDownList
ddlnames.Items.Insert(0, new ListItem("Please select"));
}
}
上面的代碼提取ItemNames及其各自的ItemCodes。
現在,要在選擇的文本框中顯示代碼,我將以下事件用於下拉元素
OnSelectedIndexChanged =“ ddlnames_OnChanged”
protected void ddlnames_OnChanged(object sender, EventArgs e)
{
//Encapsulates the object back as a dropdown list
DropDownList ddlnames = (DropDownList)sender;
//Finds the control in the corresponding gridview row and edits the label
GridViewRow row = (GridViewRow)ddlnames.NamingContainer;
TextBox IC = (TextBox)row.FindControl("itemCode");
IC.Text = ddlnames.SelectedValue;
}
好吧,這就是我要做的! :)希望有人有一天覺得這很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.