[英]How to populate a GridView drop-down list choices from SQL?
Here is what I want my Grid View to do. 这是我希望我的网格视图执行的操作。
My SQL table Pharmacy_Data contains Item_Name and Item_Code 我的SQL表Pharmacy_Data包含Item_Name和Item_Code
Populate the Item_Code from Pharmacy_Data table. 从Pharmacy_Data表填充Item_Code。 When I select the Item Name from the dropdown, It should fill the Item Code in the field.
当我从下拉列表中选择项目名称时,它应该在字段中填写项目代码。
How do I go about this? 我该怎么办?
1.将Item name dropdownlist的Autopostback设置为true,并在dropdownlist change事件内写入用于获取数据(Item code)的代码并填写Item code
I resolved this issue by adding a OnRowDataBound function to my GridView. 我通过向我的GridView添加OnRowDataBound函数解决了此问题。
OnRowDataBound="Grid_ItemList_RowDataBound" 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"));
}
}
The above code pulls the ItemNames and their respective ItemCodes. 上面的代码提取ItemNames及其各自的ItemCodes。
Now, to display the codes in the textbox on selection, I used the below event for the dropdown element 现在,要在选择的文本框中显示代码,我将以下事件用于下拉元素
OnSelectedIndexChanged="ddlnames_OnChanged" 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;
}
Well, that's what I had to do! 好吧,这就是我要做的! :) Hope someone finds this useful someday.
:)希望有人有一天觉得这很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.