在GridView Header Row DropDownList中选择标题列映射

时间:2016-07-18 15:38:44

标签: c# asp.net gridview

我创建了一个应用程序,它将映射数据并保存数据字段。对于我的GridView中的第一行,我添加了带有下拉列表的新HearerRow。 以下是我附上的代码。

我的HTML网页代码:

<asp:GridView ID="gvDataMapping" runat="server" AutoGenerateColumns="false">
</asp:GridView>

代码背后:

for (int i = 0; i < dtValues.Columns.Count; i++)
{
   BoundField boundfield = new BoundField();
   boundfield.DataField = dtValues.Columns[i].ColumnName.ToString();
   boundfield.HeaderText = dtValues.Columns[i].ColumnName.ToString();
   gvDataMapping.Columns.Add(boundfield);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();

GridViewRow HeaderGridRow = new GridViewRow(0, 0, DataControlRowType.Header,
                            DataControlRowState.Insert);
DropDownList ddlFieldValues;
TableCell HeaderCell;
foreach (DataColumn dc in dtValues.Columns)
{
    ddlFieldValues = new DropDownList();
    ddlFieldValues.ID = "FieldValues";
    ddlFieldValues.DataSource = (DataTable)Session["WorkItemTypeField"];
    ddlFieldValues.DataTextField = "FieldName";
    ddlFieldValues.DataValueField = "FieldID";
    ddlFieldValues.DataBind();
    ddlFieldValues.Items.Insert(0, new ListItem("", "0"));
    HeaderCell = new TableCell();
    HeaderCell.Controls.Add(ddlFieldValues);
    HeaderGridRow.Cells.Add(HeaderCell);
}
gvDataMapping.DataSource = dtValues;
gvDataMapping.DataBind();
gvDataMapping.Visible = true;
lblDataMapping.Visible = true;
gvDataMapping.Controls[0].Controls.AddAt(1, HeaderGridRow);

请参阅Click here to view screen displays the output of above code。单击“保存”时,未使用下面的代码将GridView Header DropDowmList显示为null。

            GridViewRow gvrow2 = gvDataMapping.HeaderRow;
            foreach (GridViewRow row in gvDataMapping.Rows)
            {
                for (int i = 0; i < gvDataMapping.Columns.Count; i++)
                {
                    String header = gvDataMapping.Columns[i].HeaderText; //gets column name
                    DropDownList cellText = ((DropDownList)gvrow2.Cells[i].FindControl("FieldValues")); //Not getting the DDL returns null
                }
            }

如何在保存点击事件中获取GridView标题行下拉列表值?

1 个答案:

答案 0 :(得分:0)

没有保证,因为我自己没有尝试过,但这段代码怎么样?

        GridViewRow gvrow1 = GrdDynamic1.HeaderRow;
        foreach (GridViewRow row in GrdDynamic1.Rows)
        {
            for (int i = 0; i < GrdDynamic1.Columns.Count; i++)
            {
                String header = GrdDynamic1.Columns[i].HeaderText;
                DropDownList cellText = ((DropDownList)gvrow1.Cells[i].FindControl("FieldValues"));
            }
        }

看起来您正在寻找右栏中的下拉列表,但不是右侧行:您正在查看数据行,而不是标题行gvrow1