Load csv file to DataTable (C#) : CSV « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" Debug="true" %>
<script runat="server">

private void Page_Load(object sender, System.EventArgs e)
{
  if(!IsPostBack)
  {
    string MyFileName;
    System.IO.StreamReader ObjectStreamReader = null;
    System.Data.DataTable ColorTable = new System.Data.DataTable("colors");
    String[] fileRow;
    System.Data.DataColumn dc;
    System.Data.DataRow dr;

    dc = new System.Data.DataColumn("Hex",typeof(string));
    ColorTable.Columns.Add(dc);
    dc = new System.Data.DataColumn("String",typeof(string));
    ColorTable.Columns.Add(dc);

    MyFileName = Page.MapPath("Data.csv");

    try 
    {
      ObjectStreamReader = new System.IO.StreamReader (MyFileName);
      while (ObjectStreamReader.Peek() > -1) {
        dr = ColorTable.NewRow();
        fileRow = ObjectStreamReader.ReadLine().Split(',');
        dr[0] = fileRow[0];
        dr[1] = fileRow[1];
        ColorTable.Rows.Add(dr);
      }
      Label1.Text = "Select a color:";    
      DropDownList1.DataSource = ColorTable;
      DropDownList1.DataTextField = "String";
      DropDownList1.DataValueField = "Hex";
      DropDownList1.DataBind();

    } 
    catch (Exception ObjectError) 
    {
      Label1.Text = ObjectError.Message;
      DropDownList1.Visible = false;
    } 
    finally 
    {
      if (ObjectStreamReader != null) 
      {
        ObjectStreamReader.Close();
      }
    }
  }  
}
</script>
<html>
  <head>
  </head>
  <body>
    <form runat="server">
      <asp:Label id="Label1" runat="server"></asp:Label>
      <asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
    </form>
  </body>
</html>








18.43.CSV
18.43.1.Create connection to csv text based database (C#)
18.43.2.Load csv file to DataTable (C#)
18.43.3.Load csv file to DataTable (VB)