Gridview控件绑定DropDownlist

时间:2014-11-01 09:24:25

标签: c# asp.net gridview

请帮我解决这个问题。我的页面上有一个GridView控件,其中包含2个下拉列表(大学和学院)。大学受page_load事件约束,而大学依赖于Uninversity.selectedValue。我有一个添加按钮,可以在网格中添加一个新行。

问题是当有超过1行时。我无法确定在onselectedIndexChanged事件中绑定哪所大学。它继续绑定第一排的大学。

这是我迄今为止在SelectedIndexChanged方法中所做的工作

    protected void drpUniversityName_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRowEventArgs e1 = (GridViewRowEventArgs)e; // Gives me a casting error on this line 
        DropDownList drpUniversityName = (DropDownList)(e1.Row.FindControl("drpUniversityName"));
        DropDownList drpCollegeName = (DropDownList)(e1.Row.FindControl("drpCollegeName"));
        bindColleges(drpUniversityName,drpCollegeName);
    } 

我需要一些方法来获得当前排的大学和学院。

1 个答案:

答案 0 :(得分:0)

<asp:GridView ID="GridView1" runat="server" >
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlUniversity" runat="server" AutoPostBack="True" 
                            onselectedindexchanged="ddlUniversity_SelectedIndexChanged">
                            <asp:ListItem>1</asp:ListItem>
                            <asp:ListItem>2</asp:ListItem>
                            <asp:ListItem>3</asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlCollege" runat="server">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

这是c#代码:

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

    private void GridView_DataBind()
    {
        string[] datasource = { "1", "2", "3" };

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

    protected void ddlUniversity_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow currentRow = (GridViewRow)((Control)sender).NamingContainer;

        //your code here
    }