获取下拉列表值c#asp时避免回发

时间:2017-11-07 09:48:08

标签: c# asp.net gridview pageload

我在C#中动态创建了dropdownlist(asp中没有代码):

DropDownList myDDL = new DropDownList();

这不能从pageLoad()调用,因为每次页面刷新时都不会加载。{p>但是,每次加载另一个dll的OnPostback(OnSelectedIndexChanged())时都会加载它,所以我不能!IsPostBack

此dll在以下时间创建:

  • 另一个dropdownlist的值使用GridView填充OnSelectedIndexChanged()

    <asp:DropDownList id ="select1" name="assignGetForm"  runat="server" class="selectClass" AutoPostBack="True" OnSelectedIndexChanged="populateGridView">
    
  • GridView上运行一个函数OnRowDatabound()(当上面的OnIndexChanged()填充它时)以填充{{1}中的 myDDL }

    GridView

我现在正尝试使用按钮<asp:GridView id="GridView1" name="GridView1" onrowdatabound="populateCellsDDL" runat="server"></asp:GridView> 事件访问myDDL中的值 - 但是这总是回发并刷新页面,以便onclick()消失,当我打印时控制它的值只是给出我的第一个值myDDL,而不是我实际选择的值。

如果更改这些值,我将如何获取这些值,因为{d}未填充在select activity上。 我曾尝试过关注AJAX,但我不确定如何通过此查看c#值。我试过pageLoad()但我没有运气,因为它没有填充viewstates

1 个答案:

答案 0 :(得分:2)

我认为,如果要访问动态创建的控件的值,则需要在每个回发中重新绑定网格。

我尝试使用以下示例代码模拟情况,并且我能够成功访问该值。

ASPX代码

<asp:DropDownList ID="select1" name="assignGetForm" runat="server" class="selectClass" AutoPostBack="True" />
<asp:GridView ID="GridView1" name="GridView1" OnRowDataBound="GridView1_DataBound" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

背后的C#代码

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        FillMainDll();

    if (!IsPostBack || GridView1.Rows.Count > 0)
        BindGrid();
}

private void FillMainDll()
{
    select1.DataSource = new int[] { 1, 2, 3 };
    select1.DataBind();
}

private void BindGrid()
{
    var dt = new DataTable();

    dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
    dt.Columns.Add(new DataColumn("Name", typeof(string)));

    for (int i = 1; i < 5; i++)
    {
        DataRow dr = dt.NewRow();

        dr[0] = i;
        dr[1] = "Name - " + i.ToString();

        dt.Rows.Add(dr);
    }

    GridView1.DataSource = dt;
    GridView1.DataBind();
}

protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var myDDL = new DropDownList();
        myDDL.ID = "myDDL";
        myDDL.DataSource = GetGridRowDdlData();
        myDDL.DataBind();
        e.Row.Cells[1].Controls.Add(myDDL);
    }
}

private IEnumerable<string> GetGridRowDdlData()
{
    var data = new List<string>();

    for (int i = 1; i < 4; i++)
    {
        data.Add("Name - " + i * int.Parse(select1.SelectedValue));
    }

    return data;
}

protected void Button1_Click(object sender, EventArgs e)
{
    var sb = new System.Text.StringBuilder();

    foreach (GridViewRow row in GridView1.Rows)
    {
        var myDDL = row.FindControl("myDDL") as DropDownList;
        if (myDDL != null)
        {
            sb.AppendFormat("{0}<br/>", myDDL.SelectedValue);
        }
    }

    Response.Write(sb.ToString());
}