我通过向我的 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;
}
好吧,这就是我必须做的! :)
希望有一天有人会发现这很有用。