如何在gridview中的下拉列表中调用函数?

时间:2016-11-23 10:23:59

标签: c# asp.net gridview

我有一个GridView,对于其中一个列我使用显示用户列表的下拉列表:

<asp:GridView  style="float:left"  
    ID="gvBookings" 
    ShowHeaderWhenEmpty="true"
    CssClass="tblResults" 
    runat="server" 
    OnRowDataBound="gvBookings_RowDataBound"                           
    DataKeyField="ID" 
    AutoGenerateColumns="false"
    allowpaging="false"
             <Columns>       
                <asp:BoundField DataField="FinishDate" HeaderText="Finish Date"></asp:BoundField>
                <asp:TemplateField HeaderText="Time Spent By">
                   <ItemTemplate>
                       <asp:DropDownList id="ddlUsers" runat="server" ></asp:DropDownList>
                   </ItemTemplate>
                </asp:TemplateField>
            </Columns>
</asp:GridView>

在后面的代码中,我需要调用一个在更改下拉列表时更新数据库的函数。我已经为FinishDate列做了这个,所以在下拉菜单中有类似的方法吗?

代码背后:

protected void gvBookings_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        BHTaskClass.BookingTask booking = (BHTaskClass.BookingTask)e.Row.DataItem;
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
             foreach (TableCell c in e.Row.Cells)
             {
                if (count == 1)
                {
                    string FinishTime = booking.FinishTime.HasValue ? booking.FinishTime.Value.ToString("hh':'mm") : "";
                    c.Text = "<input type=\"text\" id=\"txtFinishTime" + booking.ID + "\" style=\"width:70px\" type=\"text\" onblur=\"UpdateFinishTime(" + booking.ID + ",this.value)\"   value=\"" + FinishTime + "\" >";
                }
                if (count == 2) 
                {
                    ddlUsers.SelectedValue = booking.TimeSpentName;
                }
                     count++;
             }
         }
    }

因此,当FinishDate文本框被更改时,它会调用UpdateFinishTime函数并更新数据库。如何为下拉列表调用函数?

2 个答案:

答案 0 :(得分:1)

<强> ASPX

<asp:DropDownList id="ddlUsers" runat="server" 
       AutoPostBack="true" 
       OnSelectedIndexChanged="YourFunction_Changed">
</asp:DropDownList>

代码背后:

protected void YourFunction_Changed(object sender, EventArgs e)
{
    //do stuff...
}

答案 1 :(得分:0)

要获取行ID,您可以按以下方式执行

protected void YourFunction_Changed(object sender, EventArgs e)
{
   //do stuff...
   int Index = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;

  // your logic follows based on the Index 
}