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

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();
            }
        }
    }
//*
//*
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! 

Share:    
Satinder Singh

Hi all, am Founder and Author of Codepedia.info, also atypical polyglot programmer from Bombay, India. I have a passion to create, solve, and deploy software applications.
       ForEach ( minute in MyLife ) { myExperience++ ; }


10 comments on “How to Bind Dropdownlist Inside Gridview Edit Template Asp.net C#”

  1. Shashi

    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

    • Satinder singh

      That’s easy, you just need to create a new page as myProfile.aspx and add textboxes and FileUpload control and button.
      On button click get all the values and then fire your update query. In your case SQL query would be like
      update TableName set userName==’val2′,email=’val3′ ,countryID =’val4′, photo=’val5′ where regID=’uniqueId’ .

      For uploading photo, you can check at Upload Photo in Asp.net C#

      Note: While login save the unique user id into Session variable, so you can use it in your update query


Post Comment


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