We help IT Professionals succeed at work.

Bind single column table to drop down list

I'm missing something simple here. My code is collecting the appropriate data (verified this using breakpoints), but my drop down list populates each item with the text System.Data.DataRowView instead of the actual string value.
MultiView1.ActiveViewIndex = 1

        Dim Table1 As DataTable
        Table1 = New DataTable("DAT List")

        Dim datFiles As DataColumn = New DataColumn("Files")
        datFiles.DataType = System.Type.GetType("System.String")
        Table1.Columns.Add(datFiles)

        Dim datFile As String() = IO.Directory.GetFiles(txtPath.Text & "\SnapDriveInfo\")
        Dim file = From p In datFile Where p.Contains(".dat") Select p


        For Each log In file
            txtOut.Text &= log
            txtOut.Text &= vbCrLf
            Dim Row1 As DataRow
            Try
                Row1 = Table1.NewRow()
                Row1.Item(datFiles) = log
                Table1.Rows.Add(Row1)
            Catch ex As Exception

            End Try


        Next

        drpDatFiles.DataSource = Table1
        drpDatFiles.DataBind()

Open in new window

Comment
Watch Question

Before calling DataBind() you need to set DataTextField and DataValueField of the DropdownList to appropriate columns of your datatable. See this.
BRONZE EXPERT
Commented:
Replace this

 drpDatFiles.DataSource = Table1
        drpDatFiles.DataBind()


with


 drpDatFiles.DataSource = Table1
drpDatFiles.datatextfield = "Files"
drpDatFiles.dataValueField = ""Files"
  drpDatFiles.DataBind()

 

Author

Commented:
Ahh excellent! I knew it had to be something simple I was overlooking.

Thank you!

Author

Commented:
And you answered the next piece of my research before I even started looking at it. In the end I need the text field to be the name of the file and the value field to be the full path.

Thank you!
Kiran SonawaneProject Lead
BRONZE EXPERT
Top Expert 2011

Commented:
You can do like this

List<System.Web.UI.WebControls.ListItem> files = new List<System.Web.UI.WebControls.ListItem>();

 files.Add(new ListItem("Select file", "0"));
int  i =1
foreach (log in file )
{
   files.Add(new ListItem(log.toString(), i.toString()));
   i++;
}

 drpDatFiles.DataSource = files;
  drpDatFiles.DataBind();

Explore More ContentExplore courses, solutions, and other research materials related to this topic.