0

In the OnRowDataBoundevent of the ASP.Net GridView I am trying to populate the Department DropDownList (ddlDepts) which will be displayed when a row is edited.

The code below is not working as the DropdownList is empty.

Any ideas what I am doing wrong?

'//GridView markup:

  <asp:TemplateField HeaderText="Department" ItemStyle-Width = "150">
    <ItemTemplate>
        <asp:Label ID = "lblDept" runat="server" Text='<%# Eval("deptName")%>'></asp:Label>
        <asp:DropDownList ID="ddlDepts" runat="server" Visible = "false">
        </asp:DropDownList>
    </ItemTemplate>
   </asp:TemplateField>

''//Codefile

Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim cmd As New SqlCommand("SELECT DISTINCT(DeptID,DeptName) FROM Departments")
        Dim ddlDepts As DropDownList = TryCast(e.Row.FindControl("ddlDepts"), DropDownList)
        ddlDepts.DataSource = Me.ExecuteQuery(cmd, "SELECT")
        ddlDepts.DataTextField = "DeptID"
        ddlDepts.DataValueField = "DeptName"
        ddlDepts.DataBind()
        Dim DeptName As ListItem = ddlDepts.Items.FindByValue("lblDept")
        If DeptName IsNot Nothing Then
            ddlDepts.SelectedValue = DeptName.Value
        End If
    End If
End Sub
Hadi
  • 36,233
  • 13
  • 65
  • 124
Tairoc
  • 635
  • 1
  • 6
  • 18
  • Where are you initializing a connection to the database that contains the departments table? – nobody Feb 10 '17 at 20:57
  • Possibly silly question, but are you certain your OnRowDataBound event is actually firing at all? – David W Feb 10 '17 at 21:01
  • @inquisitive_mindm great question. I had it and started tinkering with the code and removed it in error. It is below: gvInPerson.DataSource = GetData(cmd) and connection to DB was defined in getData() sub. It did not help. David W, no such thing as silly question but not sure why it would be firing though. – Tairoc Feb 10 '17 at 21:26

1 Answers1

0

Not sure which SQL you are using, but I think the query may be incorrect.

In MS SQL you would use it like this:

SELECT DISTINCT DeptID, DeptName FROM Departments

And I have no knowledge of MySQL (or other databases), but a quick search seems to indicate it uses the same methods for distinct.

Community
  • 1
  • 1
VDWWD
  • 35,079
  • 22
  • 62
  • 79