0

I have a grid view, if the database is returning null for a particular column I want to insert a drop down list that is populated from a database.

Here is the code I have to identify the the column is null and it is working correctly.

protected void viewThemeTypeAssociationsGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.Cells[1].Text == " ")
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
         //fill current rows cell with a dropdown list
     }
}

Additionally, once I populate the row, how do I know which drop down list specifically is being used when there are many versions of it?

ataravati
  • 8,891
  • 9
  • 57
  • 89
David Tunnell
  • 7,252
  • 20
  • 66
  • 124
  • call findControl to find dropdown and add text and value to it. that is just theory. here someone had ask similler question. http://stackoverflow.com/questions/7305905/dropdownlist-in-gridview-asp-net – AJP Jul 26 '13 at 20:52
  • 1
    Aside: Put the `e.Row.RowType` check outside of the `e.Row.Cells` check--it will be more efficient that way. – Garrison Neely Jul 26 '13 at 20:59

1 Answers1

3

Make the potentially populated drop down list a part of the row template. Make the drop down list not visible by default and then only make it visible if you populate it with data from the database.

Without seeing your code, I am guessing that you are using TemplateFields to define your columns in your grid view, like this:

<asp:GridView id="viewThemeTypeAssociationsGridView" ruant="server" OnRowDataBound="viewThemeTypeAssociationsGridView_OnRowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="FirstName" SortExpression="FirstName">
            <ItemTemplate>
                <asp:DropDownList id="DropDownList1" runat="server" Visible="False">
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now for each row in your grid view, when you are in the RowDataBound event, you can find the drop down list, like this:

if (e.Row.RowType == DataControlRowType.DataRow)
{
     // Find the drop down list by name
     DropDownList theDropDownList = (DropDownList)e.Row.FindControl("DropDownList1");

     // Go get data from database and populate the drop down list

     // Change visibility of drop down list here
     theDropDownList.Visible = true;
}

Note: There will be one control named DropDownList1 in each row of the grid view and the FindControl() method gets the "right one" for the row you are working with.

thak777
  • 3
  • 3
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80