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

/ / 12 Comments

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 drop-down list bind. Also using `DataRowView` we were able to get and set gridview edit template drop-down list value.

Here will show an example of how to bind data to Asp.net Dropdown 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 an item template to display data .i.e (we are going to show employee name, gender, location, and department).

Now we want to edit the department for the selected employees. So now we added a drop-down list under the 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 the page_load event will call this function, and now whenever the page gets load, function gvBind() gets call and data gets to 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 the dropdown list in Gridview which we placed under the 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();
            }
        }
    }
//*

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

  Yeah, we are done now. 

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 thank me? 👳 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