How to Bind Dropdownlist Inside Gridview Edit Template Asp.net C#

/ / 12 Comments

[ads]Overview:  This article explains how to bind drop down list control which is placed inside Asp.net Gridview control under Edit Template. .i.e Gridview edit template dropdownlist bind. Also using `DataRowView` we able to get and set gridview edit template drop-down list value.

Here will show an example on how to bind data to Asp.net Drop down list control of Gridview control placed under Edit Template.

Steps to bind drop-down list in Gridview while Editing.

1) Add Html markup i.e (Gridview) 2) On Page load bind Gridview control. 3) On RowDataBound bind Dropdownlist.


Html markup:

Here first we add a Gridview control, by just drag and drop on our web page. Now will use item template to display data .i.e (we are are going to show employee name, gender, location, and department).

Now we want to edit the department for selected employee. So now we added a drop-down list under edit template, which will display only on edit mode. Our final HTML looks like as written below.

//*
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" 
onrowcancelingedit="gv_RowCancelingEdit" onrowediting="gv_RowEditing" 
onrowdatabound="gv_RowDataBound">
<Columns>
	<asp:TemplateField HeaderText="Name">
		<ItemTemplate>
			<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>
	<asp:TemplateField HeaderText="Gender">
		<ItemTemplate>
			<asp:Label ID="Label2" runat="server" Text='<%# Eval("Gender") %>'></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>
	<asp:TemplateField HeaderText="Location">
		<ItemTemplate>
			<asp:Label ID="Label3" runat="server" Text='<%# Eval("Location") %>'></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>
	<asp:TemplateField HeaderText="Department">
		<EditItemTemplate>
			<asp:DropDownList ID="ddl_department" runat="server">
			</asp:DropDownList>
		</EditItemTemplate>
		<ItemTemplate>
			<asp:Label ID="Label4" runat="server" Text='<%# Eval("department_name") %>'></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>
	<asp:TemplateField ShowHeader="False">
		<EditItemTemplate>
			<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" 
				CommandName="Update" Text="Update"></asp:LinkButton>
			&nbsp;<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" 
				CommandName="Cancel" Text="Cancel"></asp:LinkButton>
		</EditItemTemplate>
		<ItemTemplate>
			<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" 
				CommandName="Edit" Text="Edit"></asp:LinkButton>
		</ItemTemplate>
	</asp:TemplateField>
</Columns>
</asp:GridView>
//*

Page_load Bind gridview control:

This is a simple task, we made a common function `gvBind()` which binds our Gridview control with data.

On page load will call this function, and now whenever the page gets load, function gvBind() gets call and data gets display. Our final code looks as shown below.

//*
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack) {
        gvBind();
    }
}

public void gvBind()
{   
    string query="select Name,Gender,Location,department_name,department_id from myTable";
    SqlDataAdapter dap = new SqlDataAdapter(query, conn);
    DataSet ds = new DataSet();
    dap.Fill(ds);
    gv.DataSource = ds.Tables[0];
    gv.DataBind();
}
//*

On RowDataBound: Bind drop-down list

Now we are at the main part of this article .i.e we are going to bind dropdown list in Gridview which we placed under edit template.

Just look at HTML markup you will see `ddl_department` named drop-down list added. On RowDataBound by using `FindControl` will get the dropdown list and then bind it with our DataTable.

Bonus : Now in edit mode we will set gridview dropdown list selected value as it displays before edit mode.

For this, we are using `DataRowView` and able to set dropdown list default selected value. The final code looks like as written below.

//*
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_department");
                
                //return DataTable havinf department data
                DataTable dt = getDepartment(); 
                ddList.DataSource = dt;
                ddList.DataTextField = "dpt_Name";
                ddList.DataValueField = "dp_Id";
                ddList.DataBind();

                DataRowView dr = e.Row.DataItem as DataRowView;
                ddList.SelectedValue = dr["department_id"].ToString();
            }
        }
    }
//*

[txt_ads]

//*
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
    gv.EditIndex = e.NewEditIndex;
    gridviewBind();// your gridview binding function
}
//*

  Yeah, we are done now :-) Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time! 

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to do a favor, then Buy me a coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

12 Comments

  1. Shashi 08/24/2015 07:14:36
    I have a simple form called registration.aspx for users. Its works fine and save to database . regID, userName,email ,countryID (interger,FK), photo . How can I make a edit profil page for the users where they can edit the information
  2. Mike 12/02/2015 22:07:01
    Thank you! You saved me a lot of time and this worked great.
  3. Ganesh M Singare 05/18/2016 11:02:16
    very nice post thanks.
  4. Ishwar R Bhadarge 06/14/2016 09:48:25
    Nice post......thanks
  5. Roi 10/16/2016 15:02:38
    Thanks, you helped so much!!!
  6. Akash 10/27/2016 07:44:31
    Can you please make a edituserprofile
  7. Satinder singh 11/10/2016 13:16:15
    Hi Roi, thanks for the reading
  8. Naman 12/26/2016 07:30:40
    Where is the definition for the function getDepartment? it is used here:- DataTable dt = getDepartment();"
  9. Satinder singh 04/06/2017 15:47:48
    Hi Naman, Function getDepartment() is return DataTable which use to bind Dropdownlist nothing else.
  10. John Moreno 12/20/2017 15:45:25
    muchas gracias por la ayuda excelente me ayudo mucho saludos desde Perú
  11. Satinder singh 12/28/2017 17:13:19
    Sorry, I understand english only
  12. Ankita 04/24/2018 12:32:24
    How do you hide this Dropdown on Gridview display and show only when Edit is clicked? Also how to select another cell value for same row (which is edited) to send this as parameter to get datatable from database to bind dropdown.