Gridview中动态创建的Dropdownlist不会在第二次触发事件

时间:2016-09-02 07:14:41

标签: c# asp.net gridview

我一直在开发一个网页,它使用n个在网格视图中动态绑定的下拉列表。我想基于dropdownlist的selectedindexchanged事件执行操作。我已经做到了并且运作良好,但是当我第二次更改dropdownlist时它会回发但不会调用该事件。

你可以在这里看到我的代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridDropDownTest.aspx.cs"
Inherits="gridDropDownTest" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">    <div>        <asp:GridView ID="gridLedgeDetails" runat="server" OnRowDataBound="OnRowDataBound"
        OnDataBound="gridLedgeDetails_DataBound">        </asp:GridView>
</div>
</form></body></html>


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class gridDropDownTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        databind();
    }
    public void databind()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Mode");
        dt.Rows.Add("");
        dt.Rows.Add("");
        gridLedgeDetails.DataSource = dt;
        gridLedgeDetails.DataBind();
    }
    protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlMode = new DropDownList();
            ddlMode.Width = 90;
            ddlMode.Attributes.Add("style", "background-color:#ff6600;");
            ddlMode.Items.Add("Regular");
            ddlMode.Items.Add("Monthwise");
            ddlMode.SelectedIndexChanged += new EventHandler(ddlMode_Indexchanged);
            ddlMode.AutoPostBack = true;
            ddlMode.ID = "ddlMode_";
            e.Row.Cells[0].Controls.Add(ddlMode);
        }
    }
    protected void gridLedgeDetails_DataBound(object sender, EventArgs e) { }
    protected void ddlMode_Indexchanged(object sender, EventArgs e)
    {
        string uid = this.Page.Request.Params.Get("__EVENTTARGET");
        if (uid != null && uid.Contains("ddlMode_"))
        {
            string[] values = uid.Split('$');
            string row = values[1].Replace("ctl", "");
            Control ctrl = Page.FindControl(uid);
            DropDownList ddl = (DropDownList)ctrl;
            if (ddl.SelectedIndex == 1)
            {

            }
        }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:0)

为此,您需要在Page_PreInit页面方法中再次获取并绑定下拉列表。

例如......

protected void Page_PreInit(object sender,EventArgs e)

{

//这里你需要再次构建gridview。

//然后状态将保持不变......

}