[英]How to dynamically populate the ID of a column in a bound ASP.NET GridView
[英]ASP.NET gridview - how to add dynamically populated dropdown to dynamically bound gridview
我已經到處尋找有關我的問題的答案,但是我沒有發現任何結論。 我想了解以下內容:我有一個帶GridView的asp.net表單,該表單未綁定到數據源,因此沒有預定義的列。 我用來自SQL Server的數據動態填充gridview:
gvComponentLocks.DataSource = getComponentsAndLocks(worksPermitID);
//Note getComponentsAndLocks encapsulates the database query and returns a DataTable
gvComponentLocks.DataBind();
現在,我想在GridView的特定列中有一個DropDownList。 這個DropDownList應該動態地填充值(這里我認為... Item.Add是合適的方法)。 我最大的問題是如何在單元格中創建DropDownLists,而又不能在網頁的標記中將它們靜態定義為asp:TemplateField?
回答我的問題的另一種方法是如何使用數據源中的數據動態填充靜態定義的GridView(具有靜態定義的DropDownList控件),而無需將GridView靜態綁定到DataSource。
假定GridView(具有靜態定義的DropDownList控件)
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
在側面
protected void gvComponentLocks_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
做類似...
DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");
DropDownList1.DataSource=SomeDropDownList1ItemCollection
DropDownList1.Bind();
或者從ListItemCollection返回,最好是...
gvComponentLocks.Items.AddRange(LoadList().Cast<ListItem>().ToArray());
哪里
public ListItemCollection LoadList()
{
ListItemCollection Items = new ListItemCollection();
Items.Add(new ListItem("Choose from list...", ""));
Items.Add(new ListItem("Text","Value")
動態DropDownList:將PlaceHolder控件放入網格中的模板。 在后面的代碼中使用適當的ID創建一個DropDownList控件,然后將其添加到PlaceHolder控件中。
DropDownList DropDownList1= new DropDownList();
DropDownList1.ID=...
etc
YourPlaceHolderControl.Controls.Add(DropDownList1)
您將必須在回發時重新構建此動態DropDownList並重新填充它。
您可以在GridView的RowDataBound
事件中動態創建DropDownList。
protected void gvComponentLocks_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//create a new dropdownlsit
DropDownList ddl = new DropDownList();
//bind the source and define the values
ddl.DataSource = getComponentsAndLocks(worksPermitID);
ddl.DataTextField = "columnA";
ddl.DataValueField = "columnB";
ddl.DataBind();
//add the dropdownlist to the gridview in column 1
e.Row.Cells[1].Controls.Add(ddl);
}
}
您還要做的唯一一件事就是將GridView的DataBBinding放置在IsPostBack
檢查之外。 否則,您將在回發后丟失DropDowns。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.