Search code examples
asp.netgridviewgridviewcolumn

Multiple databound controls in a single GridView column


I have a grid view that is data bound to a dataset. In a grid I have a column DefaultValue, which has three controls in it - a dropdownlist, a checkbox and a textbox. Depending on the data that is coming in it can switch to any of these controls. Everything is simple enough when we need just to display data - in gridview_prerender event I simply make one of the controls visible. The control is setup like following:

<asp:TemplateField HeaderText="Default Value" SortExpression="DefaultValue">
 <ItemTemplate>
  <asp:TextBox ID="txt_defaultValue_view" runat="server" Text='<%# Bind("DefaultValue") %>' Enabled ="false" />
  <asp:DropDownList ID="ddl_defaultValue_view" runat="server" Enabled ="false" />
  <asp:CheckBox ID="chk_defaultValue_view" runat="server" Enabled ="false"  />
 </ItemTemplate>
 <EditItemTemplate>
  <asp:TextBox ID="txt_defaultValue_edit" runat="server" Text='<%# Bind("DefaultValue") %>'/>
  <asp:DropDownList ID="ddl_defaultValue_edit" runat="server" />
  <asp:CheckBox ID="chk_defaultValue_edit" runat="server" />
 </EditItemTemplate>
</asp:TemplateField>

My problem starts when I am in edit mode and I need to update the grid with new data. Since only the textbox control is databound, the RowUpdating event can only access data from the textbox column and all of my other data simply gets discarded. I also can't databind with checkbox and dropdownlist control, since they can get an invalid data type exception. So, does anyone know how can I update a column that has three different controls, where each of these three controls might have a valid data?

Thanks


Solution

  • First, i would switch visibility of the controls in RowDataBound of the Grid and not on PreRender, because it can only change on DataBinding and not on every postback. You can there also bind the Dropdown to its datasource, change the checked-state of the Checkbox and set the Text-property of the Textbox according to the the Dataitem of the Row. When you update you can find your controls with FindControl in RowUpdating and get their values(f.e. Dropdownlist.SelectedValue).