user123456789
user123456789

Reputation: 2004

How to call a function when drop down list in gridview is changed?

I have a GridView and for one of the columns I'm using a drop down list that displays a list of users:

<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>

In the code behind I need to call a function that updates the database when the drop down list is changed. I have done this already for the FinishDate column so is there a similar way to do this for the drop down menu?

Code behind:

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++;
             }
         }
    }

So when the FinishDate textbox is changed it calls the UpdateFinishTime function and this updates the database. How do I call a function for the drop down list?

Upvotes: 0

Views: 583

Answers (2)

Gaurav Shah
Gaurav Shah

Reputation: 343

To get the Row ID you can do it as below

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 
}

Upvotes: 0

mybirthname
mybirthname

Reputation: 18127

ASPX

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

Code behind:

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

Upvotes: 1

Related Questions