gridview DropDownList选中的值问题

时间:2009-10-02 03:12:16

标签: asp.net

在asp.net vs05上工作。我采用gridview并在RowDataBount下填充dropDownList。

<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False" DataKeyNames="StudentID" OnSelectedIndexChanged="GridView3_SelectedIndexChanged" OnRowDataBound="GridView3_RowDataBound">
            <Columns>
                <asp:BoundField DataField="StudentID" HeaderText="StudentID" ReadOnly="True" SortExpression="StudentID" />
                <asp:BoundField DataField="StudentName" HeaderText="StudentName" />
                <asp:TemplateField HeaderText="DivisionName">
                    <EditItemTemplate>

                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server" Width="160px">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:ButtonField ButtonType="Button" CommandName="Select" HeaderText="Update" Text="Update" />
            </Columns>
        </asp:GridView>



DropDownList DropDownList1 = (DropDownList)e.Row.FindControl("DropDownList1");

            studentInfos ostudentInfos = new studentInfos();
            BOstudentInfo oBOstudentInfo = new BOstudentInfo();
            ostudentInfos = oBOstudentInfo.Gets();           
            DropDownList1.DataTextField = "StudentName";
            DropDownList1.DataValueField = "StudentName";
            DropDownList1.SelectedValue = "StudentName";

            foreach (studentInfo oItem in ostudentInfos)
            {
                DropDownList1.Items.Add(oItem.StudentName);


            }

然后使用selectedIndexChanged事件

  GridViewRow selectRow = GridView3.SelectedRow;
        String ID = selectRow.Cells[0].Text;
        String Name = selectRow.Cells[1].Text;
        DropDownList ddl = (DropDownList) selectRow.FindControl("DropDownList1");

         string s = ddl.SelectedValue;

在此事件中,为什么我总是选择selectedIndex = 0和SelectedValue =列表的第一个元素。

2 个答案:

答案 0 :(得分:1)

使用 IsPostBack 页面属性。

if(!IsPostBack){
  .....
 foreach (studentInfo oItem in ostudentInfos){
    DropDownList1.Items.Add(oItem.StudentName);
  }
}

答案 1 :(得分:0)

DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.NamingContainer;
String id = row.Cells[0].Text;
string requestid = ((Label)row.FindControl("Label1")).Text;
string type = ddl.SelectedValue;