DropDownList in the GridView - Keeping asp.net forms control in GridView

SheoNarayan
Posted by in ASP.NET category on for Beginner level | Views : 51806 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, I have described the ways of keeping DropDownList in the GridView and binding the data by preserving the default SelectedValue. Apart from DropDownList, I have also shown how to keep CheckBox, RadioButtonList, TextBox in the GridView and preserving the default data.

Introduction

Problem in placing DropDownList in the GridView and preseving the SelectedValue is one of the frequently asked question I have found on the different forums. In this article, I have shown how to achieve this functionality. Apart from DropDownList, I have also shown how to keep other asp.net forms control like asp:CheckBox, asp:TextBox, asp:RadioButtonList in the GridView and preserving the selected value that is coming from the database.

Placing the DropDownList in the GridView

To place the DropDownList in the GridView, you will have to use asp:TemplateField that under <Columns>, Generally you will need to use the DropDownList in the GridView in the Edit mode (under EditItemTemplate, However this solution will work for you even if you want to place the DropDownList in the ItemTemplate) where you want your user to select the data from the DropDownList and update the record. A typical example is shown in the picture below


The aspx page code of above GridView is below

<asp:Label ID="lblMessage" runat="server" EnableViewState="true" />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" GridLines="Both" AutoGenerateEditButton="true"

OnRowCancelingEdit="GridView_CancelEdit" OnRowEditing="GridView_Edit"

OnRowUpdating="GridView_Update" DataKeyNames="PersonID" >

<Columns>

<asp:BoundField DataField="PersonID" HeaderText="Person ID" ReadOnly="True" Visible="false"/>

<asp:TemplateField HeaderText="Last Name">

<ItemTemplate>

<%# Eval("LastName") %>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Department DropDown">

<ItemTemplate>

<%# Eval("DeptName")%>

</ItemTemplate>

<EditItemTemplate>

<asp:DropDownList ID="dropDownDept" DataSource="<%# BindDropDownDepartment() %>" DataTextField="DeptName" DataValueField="DeptId" runat="server" SelectedValue='<%# Eval("DeptId").ToString() %>'>

</asp:DropDownList>

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="CustomCheckBox Field">

<ItemTemplate>

<%# Eval("Active") %>

</ItemTemplate>

<EditItemTemplate>

<asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("Active") %>' />

</EditItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="RadioButtonField">

<ItemTemplate>

<%# Eval("Active") %>

</ItemTemplate>

<EditItemTemplate>

<asp:RadioButtonList ID="radioActive" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" SelectedValue='<%# Eval("Active") %>'>

<asp:ListItem Text="True" Value="True" />

<asp:ListItem Text="False" Value="False" />

</asp:RadioButtonList>

</EditItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

Notice the bolded code for DropDownList in the above code snippet. It has a DataSource and SelectedValue attribute. I have used DataSource to specify the source of the DropDownList and the method I am calling is BindDropDownDepartment as shown below that is returning the DataTable containing the department information.

/// <summary>

/// Data source to the dropdownage

/// </summary>

/// <returns></returns>

protected DataTable BindDropDownDepartment()

{

DepartmentBAL dept = new DepartmentBAL();

return dept.LoadAll();

}

Here DepartmentBAL is by business layer object that has LoadAll method which returns DataTable

To specify the default value coming from elsewhere of any of the asp.net forms server control, you will have to use single quote ( ' ), instead of double quote ( " ). If you will specify double quote, you will get following error.

Parser Error Message: The server tag is not well formed.

Someone may say that instead of doing this, I could have used OnRowDataBound event and found the DropDownList for that particular row and bounded the DropDownList box. Well, you can do that however in that case you will not be able to maintain the default value for that record that is coming from the database which I have specified using SelectedValue attribute. If you ever tried to do that you would receive following error.

Exception Details: System.ArgumentOutOfRangeException: 'dropDownDept' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

This error is caused by the fact that the OnRowDataBound event fires when the GridViewRows is actually being bounded and at the time of binding GridView rows, the DropDownList items is not bounded so there is no way you will be able to get its items and the SelectedValue will complain that it couldn't find the item to select.

Whatever you were trying to do in the OnRowDataBound event will fire once the GridViewRow is bounded and by this time you will no way be able to specify the SelectedValue of the DropDownList in the server side.

(NOTE: If you have a better solution to do whatever I am trying to achieve using DataSource of the DropDownList , kindly respond to this article by giving your solution).

Get solutions of your .NET problems with video explanations, .pdf and source code in .NET How to's.


Binding the DropDownList in the GridView

<EditItemTemplate>

<asp:DropDownList ID="dropDownDept" DataSource="<%# BindDropDownDepartment() %>" DataTextField="DeptName" DataValueField="DeptId" runat="server" SelectedValue='<%# Eval("DeptId").ToString() %>'>

</asp:DropDownList>

</EditItemTemplate>

So the solution of the problem is as soon as the GridViewRow is ready to be bounded, your DropDownList box should already have its items bounded and you can do that by specifying its DataSource. In my case, I have called the BindDropDownDepartment method that will return the DataTable and the DropDownList box will be bounded. As my DropDownList has been bounded before GridViewRow so GridView will be able to find the SelectedValue specified in the DropDownList and that selection will be maintained as you can see in the above picture.

Binding the CheckBox in the GridView

<EditItemTemplate>

<asp:CheckBox ID="chkActive" runat="server" Checked='<%# Eval("Active") %>' />

</EditItemTemplate>

To bind the CheckBox in the GridView, sepecify the Checked attribute with the Eval("fieldName") and this will work for you. Please note that you will be able to bind the CheckBox only when your database field type is of boolean (bit in the Sql Server)

Binding RadioButtonList in the GridView

<EditItemTemplate>

<asp:RadioButtonList ID="radioActive" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" SelectedValue='<%# Eval("Active") %>'>

<asp:ListItem Text="True" Value="True" />

<asp:ListItem Text="False" Value="False" />

</asp:RadioButtonList>

</EditItemTemplate>

Binding RadioButtonList in the GridView, specify the SelectedValue as the way we had sepcified in case of DropDownList box. As my RadionButtonList box value is already known to me so I have hard coded it. If it would have come from somewhere else like from database, I would have specified the DataSource in the same way I have done for the DropDownList.

Binding TextBox in the GridView

<EditItemTemplate>

<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />

</EditItemTemplate>

Binding the TextBox is very simple, just use the Text attribute as the value that is coming from the database.

Retrieving the asp.net Forms control in the Update method

protected void GridView_Update(object sender, GridViewUpdateEventArgs e)

{

GridViewRow row = GridView1.Rows[e.RowIndex];

DropDownList dropDept = (DropDownList)row.FindControl("dropDownDept");

TextBox txtName = (TextBox)row.FindControl("txtLastName");

RadioButtonList radioAct = (RadioButtonList)row.FindControl("radioActive");

CheckBox chkAct = (CheckBox)row.FindControl("chkActive");

 

// retrieve the data from above controls and save call your method to save the data

}

You can retrieve the selected value of the controls placed in the EditIemItemplate in the Update event by finding using row.FindControl method as specified above.

To work with edit, cancel, update and delete functionality of the GridView, please read http://www.dotnetfunda.com/articles/article29.aspx. Apart from this article, there are many articles on GridView available here.

Conclusion

Hope ths article would be useful for someone struggling with keeping the DropDownList and maintaining the defualt SelectedValue in the GridView. Stay tuned in for more articles. Thanks for reading and happy learning !

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Hanzie on: 1/24/2011 | Points: 25
Hello, i believe i understand youre code correctly.
I tried it but my code failes, i tried different things but nothing works. Can you help me please.
I get folowing error: ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'UpdateTransactie' that has parameters: Naam, Omschrijving1, ID_SR, @ID_SR, ID.

My code is added as supporting file.

MANY THANKS IN ADVANCED...

Posted by: Hanzie on: 1/24/2011 | Points: 25
Hello, i believe i understand youre code correctly.
I tried it but my code failes, i tried different things but nothing works. Can you help me please.
I get folowing error: ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'UpdateTransactie' that has parameters: Naam, Omschrijving1, ID_SR, @ID_SR, ID.

Code file is added as supporting file.

Many thanks in advanced.
Posted by: Hanzie on: 1/24/2011 | Points: 25
Hello, i tried youre code but i get error:

ObjectDataSource 'ObjectDataSource1' could not find a non-generic method 'UpdateTransactie' that has parameters: Naam, Omschrijving1, ID_SR, @ID_SR, ID.

I tried for one week now but i don't get it to work, can you help me please?!! Many thanks in advanced.

Code-file is add as supporting file.

Greetings Hanzie

Login to post response

Comment using Facebook(Author doesn't get notification)