Solved

Insert dropdownlist in formview where datasoucre is a generic List(Of T)

Posted on 2014-02-18
11
301 Views
Last Modified: 2014-02-20
Hi!

In a formview, in edit mode, I am able to let the user choose from a dropdownlist if the datasource is an sql-datasource or accessdatasource, but I am not able to do it when the datasource i a List(Of T).

This  part of the code shows how I successfully include a dropdownlist with an Access-datasource


   
           Rubrik:
             <asp:DropDownList ID="dropdownlist1"
DataSourceID="Accessdatasource2"
DataTextField="Rubrik"
DataValueField="idnr"
SelectedValue='<%# Bind("IDNR") %>' runat="server" >
</asp:DropDownList>

Open in new window



This is the complete part of the formview edititem-template



<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" 
          DataSourceID="AccessDataSource1" AllowPaging="True" EnableModelValidation="True">
          <EditItemTemplate>
              ID:
              <asp:Label ID="IDLabel1" runat="server" Text='<%# Eval("ID") %>' />
              <br />
              Beskrivning:
              <asp:TextBox ID="BeskrivningTextBox" textmode="MultiLine" 
					Width=500 Rows=10 runat="server" 
                  Text='<%# Bind("Beskrivning") %>' />
              <br />
              Datum:
              <asp:Calendar  Visible="false" ID="Calendar1" runat="server" SelectedDate='<%# Bind("datum") %>' ></asp:Calendar>


              <br />
              Lank:
              
              <asp:TextBox ID="LankTextBox" runat="server" Text='<%# Eval("Lank") %>' />







              <br />
              Rubrik:
             <asp:DropDownList ID="dropdownlist1"
DataSourceID="Accessdatasource2"
DataTextField="Rubrik"
DataValueField="idnr"
SelectedValue='<%# Bind("IDNR") %>' runat="server" >
</asp:DropDownList>


<br />
              <p></p>

              <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
                  CommandName="Update" Text="Uppdatera" />
              &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
                  CausesValidation="False" CommandName="Cancel" Text="Avbryt" />
          </EditItemTemplate>

Open in new window



The problem comes when I want to add another dropdownlist with the datasoucrce= list, which I get in this way


 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        

If Not IsPostBack Then
            Dim list As New Generic.List(Of String)
            
            Dim FExtension1 As String = "*.pdf*"
   

            Dim di As DirectoryInfo = New DirectoryInfo("C:\Data\test\")
            Dim fi As FileInfo
            list.Add("   Välj fil att ta bort")
            For Each fi In di.GetFiles(FExtension1)
                

                list.Add(fi.Name)

            Next
            For Each fi In di.GetFiles(FExtension2)
               

                list.Add(fi.Name)

           
                list.Sort()
            Next

            
            DropDownList3.DataSource = list
                
            DropDownList3.DataBind()
        End If
    End Sub

Open in new window



This is the complete code:

<%@ Page Title="" Language="VB" MasterPageFile="~/2014/MasterPage.master" %>
<%@ import namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<%@ Import Namespace="System.Collections.Generic" %>
<script runat="server">
    Function InsertLink2(ByVal strIn) As String
        Dim strTmp As String
        strTmp = "<ul><a href='../../14/blanketter/" & strIn & "'>" & strIn & "</a></ul>"
        Return strTmp
	
    End Function

    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        FormView1.PageIndex = GridView1.SelectedIndex
        
        
    End Sub
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        

        If Not IsPostBack Then
            Dim list As New Generic.List(Of String)
            
            Dim FExtension1 As String = "*.pdf*"
            

            Dim di As DirectoryInfo = New DirectoryInfo(("C:\Data\test\")
            Dim fi As FileInfo
            list.Add("   Välj fil att ta bort")
            
For Each fi In di.GetFiles(FExtension1)
                

                list.Add(fi.Name)

            
                list.Sort()
            Next

            
            DropDownList3.DataSource = list
                
            DropDownList3.DataBind()
        End If
    End Sub
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>

<asp:Content ID="Content2" runat="server" contentplaceholderid="ContentPlaceHolder1">
   <asp:AccessDataSource ID="AccessDataSource1" runat="server" 
          DataFile="~/historik/13/app/blanketter.mdb" 
          SelectCommand="SELECT [ID], Rubrik,[Beskrivning], [datum], [Lank], viktigt2.[IDNR] FROM [Viktigt2] inner join [Values] on [Viktigt2].idnr=[values].idnr"
           updatecommand="UPDATE [Viktigt2] SET [Beskrivning] = ?, [datum] = ?, [Lank] = ?, [IDNR] = ? WHERE [ID] = ?"
          DeleteCommand="DELETE FROM [Viktigt2] WHERE [ID] = ?" 
          
          InsertCommand="INSERT INTO [Viktigt2] ( [Beskrivning], [datum], [Lank], [IDNR]) VALUES ( ?, ?, ?, ?)">
    <DeleteParameters>
        <asp:Parameter Name="ID" Type="Int32" />
    </DeleteParameters>
    <UpdateParameters>
        <asp:Parameter Name="Beskrivning" Type="String" />
        <asp:Parameter Name="datum" Type="DateTime" />
        <asp:Parameter Name="Lank" Type="String" />
        <asp:Parameter Name="IDNR" Type="String" />
        <asp:Parameter Name="ID" Type="Int32" />
    </UpdateParameters>
    <InsertParameters>
        <asp:Parameter Name="Beskrivning" Type="String" />
        <asp:Parameter Name="datum" Type="DateTime" />
        <asp:Parameter Name="Lank" Type="String" />
        <asp:Parameter Name="IDNR" Type="String" />
    </InsertParameters>
      </asp:AccessDataSource> 
      <asp:AccessDataSource ID="AccessDataSource2" runat="server" 
                      DataFile="~/historik/13/app/blanketter.mdb" 
                      SelectCommand="SELECT [IDNR], Rubrik FROM [Values]">
                  </asp:AccessDataSource>

      <asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" 
          DataSourceID="AccessDataSource1" AllowPaging="True" EnableModelValidation="True">
          <EditItemTemplate>
              ID:
              <asp:Label ID="IDLabel1" runat="server" Text='<%# Eval("ID") %>' />
              <br />
              Beskrivning:
              <asp:TextBox ID="BeskrivningTextBox" textmode="MultiLine" 
					Width=500 Rows=10 runat="server" 
                  Text='<%# Bind("Beskrivning") %>' />
              <br />
              Datum:
              <asp:Calendar  Visible="false" ID="Calendar1" runat="server" SelectedDate='<%# Bind("datum") %>' ></asp:Calendar>


              <br />
              Lank:
              
              <asp:TextBox ID="LankTextBox" runat="server" Text='<%# Eval("Lank") %>' />







              <br />
              Rubrik:
              <asp:DropDownList ID="dropdownlist1"
DataSourceID="Accessdatasource2"
DataTextField="Rubrik"
DataValueField="idnr"
SelectedValue='<%# Bind("IDNR") %>' runat="server" >
</asp:DropDownList>


<br />
              <p></p>

              <asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" 
                  CommandName="Update" Text="Uppdatera" />
              &nbsp;<asp:LinkButton ID="UpdateCancelButton" runat="server" 
                  CausesValidation="False" CommandName="Cancel" Text="Avbryt" />
          </EditItemTemplate>
          <InsertItemTemplate>
              Beskrivning:
              <asp:TextBox ID="BeskrivningTextBox" textmode=MultiLine 
					Width=500 Rows=10 runat="server" 
                  Text='<%# Bind("Beskrivning") %>' />
              <br />
              Datum:
             <asp:Calendar Visible="false" ID="Calendar1" runat="server" SelectedDate='<%# Bind("datum") %>' 
    ></asp:Calendar>
              <br />
              Lank:
              <asp:TextBox ID="LankTextBox" runat="server" Text='<%# Bind("Lank") %>' />
              <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>


              <br />
              Rubrik:
              <p></p>
              <asp:DropDownList ID="dropdownlist1"
DataSourceID="accessdatasource2"
DataTextField="Rubrik"
DataValueField="IDNR"
SelectedValue='<%# Bind("IDNR") %>' runat="server" >
</asp:DropDownList>
              <br />
              <asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" 
                  CommandName="Insert" Text="Lägg till" />
              &nbsp;<asp:LinkButton ID="InsertCancelButton" runat="server" 
                  CausesValidation="False" CommandName="Cancel" Text="Avbryt" />
          </InsertItemTemplate>
          <ItemTemplate>
              ID:
              <asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
              <br />
              Beskrivning:
              <asp:Label ID="BeskrivningLabel" runat="server" 
                  Text='<%# Eval("Beskrivning") %>' />
              <br />
              Datum:
              <asp:Label ID="datumLabel" runat="server" 
                  Text='<%# Bind("datum") %>' />
              <br />
              Lank:
              <asp:Label ID="LankLabel" runat="server" Text='<%# Eval("lank")%>' />
              <br />
              Rubrik
              <asp:Label ID="IDNRLabel" runat="server" Text='<%# Bind("idnr") %>' />
              <br />
              <asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" 
                  CommandName="Edit" Text="Ändra" />
              &nbsp;<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" 
                  CommandName="Delete" Text="Radera" />
              &nbsp;<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" 
                  CommandName="New" Text="Ny post" />
          </ItemTemplate>
                <emptydatatemplate>
          <table>
            <tr>
              <td>
               <asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" 
                  CommandName="New" Text="Ny post" />
              </td>
             
            </tr>
          </table>
        </emptydatatemplate>
      </asp:FormView>
      <asp:DropDownList ID="DropDownList3" runat="server">
    </asp:DropDownList>
      <asp:GridView ID="GridView1" runat="server" AllowSorting="True" onselectedindexchanged="GridView1_SelectedIndexChanged" ShowHeaderWhenEmpty="true"
          DataSourceID="AccessDataSource1" EnableModelValidation="True">
          <Columns>
              <asp:CommandField ShowSelectButton="True" SelectText="Redigera" />
              <asp:TemplateField>
                  <EditItemTemplate>
                      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                  </EditItemTemplate>
                  <ItemTemplate>
                      <asp:Label ID="Label1" runat="server"></asp:Label>
                  </ItemTemplate>
              </asp:TemplateField>
          </Columns>
          <emptydatarowstyle backcolor="LightBlue"
          forecolor="Red"/>

        
          
          
          
      </asp:GridView>
</asp:Content>

Open in new window

basicstructureofthepage.jpg
formview-editmode.jpg
0
Comment
Question by:marcgu
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
11 Comments
 
LVL 41

Expert Comment

by:guru_sami
ID: 39868603
Sorry...what's the issue?
0
 

Author Comment

by:marcgu
ID: 39868656
Hello!

My problem is that I can insert a dropdrownlist in this way in the formview

Rubrik:
             <asp:DropDownList ID="dropdownlist1"
DataSourceID="Accessdatasource2"
DataTextField="Rubrik"
DataValueField="idnr"
SelectedValue='<%# Bind("IDNR") %>' runat="server" >
</asp:DropDownList>



but I also want another dropdownlist in the formview. However, this dropdownlist cannot have an Accessdatasource as DatasourceID, because it will dispaly all the files in a folder.


If you look a the attached picture: formview-editmode.jpb you see that the field Rubrik has a dropdownlist but I also want a dropdownlist for the field: lank (instead of the textbox)

Hope it´s clearer now. I admit I was not to obvious what I meant.
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 39868706
Yep..now the issue is clear.
What you need to do is in the Formview OnDataBound event handler, Check if the CurrentMode=Insert then do a FindControl for your DropDownList2.

Get the list and bind it to the dropdownlist.
0
Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

 

Author Comment

by:marcgu
ID: 39871853
Hi!

Ok, I tried this way (and at least 50 other combinations without success)

 Protected Sub FormView1_DataBound(sender As Object, e As EventArgs) Handles FormView1.DataBound
        If FormView1.CurrentMode = FormViewMode.Insert Then

            Dim dropdownlist2 As DropDownList = Page.FindControl("DropDownList3")
      ' CType(Page.FindControl("ctl00_ContentPlaceHolder1_DropDownList3"),DropDownList)
        End If
    End Sub

Open in new window


And in the formview I put this


 Lank:
                           <asp:DropDownList ID="dropdownlist2"

SelectedValue='<%# Bind("Lank")%>' runat="server" >
</asp:DropDownList>

but the dropdownlist is empty in insert-mode. I probably must change the findcontrol, but I cannot find a complet code example.

I'd be grateful for advice that can lead me closer to the solution.
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 39872020
You should find it inside the FormView:
Dim dropdownlist2 As DropDownList = CType(FormView1.FindControl("DropDownList2"), DropDownList)
'Get the list
'Bind it to dropdownlist2

Open in new window

0
 

Author Comment

by:marcgu
ID: 39872641
Thanks for your patience

I now get the dropdownlist with correct values in insert -mode, but on problem remains:

Sub after your suggestions:

 
 Protected Sub FormView1_DataBound(sender As Object, e As EventArgs) Handles FormView1.DataBound

        If FormView1.CurrentMode = FormViewMode.Insert Then

            
   
            Dim dropdownlist2 As DropDownList = CType(FormView1.FindControl("DropDownList2"), DropDownList)
            Dim list As New Generic.List(Of String)
            list.Add("test2")
             list.Add("testny")
            dropdownlist2.DataSource = list
                
            dropdownlist2.DataBind()
        End If
    End Sub
</script>

Open in new window


Problem is that it only works when I omit the binding-element and then without it no data comes to the gridview. If I do not omit it I get error message:

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control

 <asp:DropDownList ID="dropdownlist2"
SelectedValue='<%# Bind("Lank")%>' runat="server" >
</asp:DropDownList>
0
 
LVL 41

Expert Comment

by:guru_sami
ID: 39874171
So do you need to set the SelectedValue when you are in insert mode?

What do you mean by: "... without it no data comes to the gridview."
How is the FormView in insertmode tied to GridView?
0
 

Author Comment

by:marcgu
ID: 39874213
Hi!

Sorry, what I meant was:

The gridview and the formview reads from the same database, so the problem should be:

 I can now see the dropdownlist in inserview, but it doesnt update the database.
0
 
LVL 41

Accepted Solution

by:
guru_sami earned 500 total points
ID: 39874317
That makes sense. Try this:
Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As FormViewInsertEventArgs) Handles FormView1.ItemInserting
        Dim ddl As DropDownList = CType(FormView1.FindControl("DropDownList2"),DropDownList)
        AccessDataSource1.InsertParameters("Lank").DefaultValue = ddl.SelectedValue
End Sub

Open in new window

0
 

Author Closing Comment

by:marcgu
ID: 39874604
Perfect solution although I had difficulites to express what my problem was. I am very, very grateful.
0

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question