Solved

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

Posted on 2014-02-18
11
294 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
  • 5
  • 5
11 Comments
 
LVL 41

Expert Comment

by:guru_sami
Comment Utility
Sorry...what's the issue?
0
 

Author Comment

by:marcgu
Comment Utility
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
Comment Utility
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
 

Author Comment

by:marcgu
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:marcgu
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Perfect solution although I had difficulites to express what my problem was. I am very, very grateful.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

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…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This video discusses moving either the default database or any database to a new volume.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now