简体   繁体   English

尝试使用asp.net和C#将CSV文件导入到SQL Server数据库-找不到我所缺少的内容

[英]Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing

I am a student and quite new to programming, and I was given a task to do using ASP.NET and C#, without being taught either. 我是一名学生,对编程还很陌生,因此我被赋予了使用ASP.NET和C#的任务,而没有一个人受教。 The plan is to learn to teach ourselves. 该计划是学会自学。

The task I am stuck on is making a website import from a CSV file to a SQL Server database of last year's room bookings around the campus. 我的任务是将网站从CSV文件导入到SQL Server数据库中,该数据库包含校园附近去年的房间预订。

The table normally has the following columns: 该表通常具有以下列:

        Request_ID;
        Priority;
        Module_ID;
        Day;
        Start_Time;
        Length;
        Park;
        Students;
        Room_Code;
        Status;
        Semester_ID;
        Linked_Request;
        Week_1;
        Week_2;
        Week_3;
        Week_4;
        Week_5;
        Week_6;
        Week_7;
        Week_8;
        Week_9;
        Week_10;
        Week_11;
        Week_12;
        Week_13;
        Week_14;
        Week_15; )

In my code, I try to make it work only 3 columns (Request_ID,Priority,Module) for starters. 在我的代码中,我尝试使其仅对初学者起作用3列(Request_ID,Priority,Module)

When I press the Import button, I want it to read a .csv file (with a fixed name at a fixed directory) eg "1,2,3" - the comma separating the fields [delimiter] - and import it into the SQL Server database. 当我按下Import按钮时,我希望它读取一个.csv文件(在固定目录中具有固定名称),例如"1,2,3" (用comma separating the fields [delimiter] )并将其导入到SQL中服务器数据库。 Then I want the data grid to show it as well. 然后,我希望数据网格也显示它。

Something like this: 像这样:

http://tinypic.com/r/50lchu/5 http://tinypic.com/r/50lchu/5

Visual studio will build my code, but when I press the "Import" button, nothing happens. Visual Studio将构建我的代码,但是当我按下“导入”按钮时,什么也没有发生。 I have been experimenting for days with this code, and I can't pinpoint where the mistake is. 我已经使用该代码进行了数天的实验,但我无法查明错误的出处。 Since the deadline is coming tomorrow, I would be grateful if someone could tell me what am I missing. 由于截止日期是明天,因此,如果有人能告诉我我想念的是什么,我将不胜感激。

Here is my code: 这是我的代码:

aspx: aspx:

<!DOCTYPE html>
<script runat="server">

    Protected Sub Import_button_Click(sender As Object, e As EventArgs)

    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs)

    End Sub
</script>
<html lang="en">

  <head>
    <meta charset="utf-8">

    <title>Timetabling Support Website</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Loading Bootstrap -->
    <link href="css/bootstrap.css" rel="stylesheet">

    <!-- Loading Flat UI -->
    <link href="css/flat-ui.css" rel="stylesheet">

     <!-- Loading Unsemantic -->
    <link href="css/unsemantic-grid-responsive.css" rel="stylesheet"> 

    <!-- Loading Personalized Style -->
    <link href="css/style.css" rel="stylesheet"> 
    <link rel="shortcut icon" href="images/favicon.ico">  


    <!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. -->
    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
    <![endif]-->
  </head>

  <body>
      <form id="form1" runat="server">
    <div class="grid-container">

      <div class="header grid-100">
        <div class="banner grid-70">
          <img src="images/banner3.png" id="banner" alt="Loughborough Uni Logo" />
        </div>
        <div class="logout grid-30">
          <p id="logout"> Welcome, Computer Science Timetabler. | <a href="index.html">Logout</a></p>
        </div>
      </div>


      <div class="navbar navbar-inverse">
          <div class="navbar-inner">
            <ul class="nav">
              <li>
                <a href="home.html">
                  Home
                </a>
              </li>
              <li>
                <a href="#">
                  Requests
                </a>
                <ul>
                  <li>
                    <a href="request_new.html">New Request</a>
                  </li>
                  <li>
                    <a href="request_import.html">Import Requests</a>
                  </li>
                  <li>
                    <a href="request_current.html">Current Requests</a>
                  </li>
                  <li>
                    <a href="request_adhoc.html">Ad-Hoc Request</a>
                  </li>
                </ul> <!-- /Sub menu -->
              </li>
              <li>
                <a href="room_availability.html">
                  Room Availability
                </a>
              </li>
              <li>
                <a href="#">
                  History
                </a>
                <ul>
                  <li>
                    <a href="#">Semester 1</a>
                    <ul>
                      <li>
                        <a href="history_s1priority.html">Priority Round</a>
                      </li>
                      <li>
                        <a href="history_s1round1.html">Round 1</a>
                      </li>
                      <li>
                        <a href="history_current.html">Round 2</a>
                      </li>
                      <li>
                        <a href="history.html">Final Allocations</a>
                      </li>
                    </ul> <!-- /Sub menu -->
                  </li>
                  <li>
                    <a href="#">Semester 2</a>
                    <ul>
                      <li>
                        <a href="history.html">Priority Round</a>
                      </li>
                      <li>
                        <a href="history.html">Round 1</a>
                      </li>
                      <li>
                        <a href="history.html">Round 2</a>
                      </li>
                      <li>
                        <a href="history.html">Final Allocations</a>
                      </li>
                    </ul> <!-- /Sub menu -->
                  </li>
                </ul> <!-- /Sub menu -->
              </li>
              <li>
                <a href="#">
                  Maintenance
                </a>
                <ul>
                  <li>
                    <a href="module_add.html">Add Module</a>
                  </li>
                  <li>
                    <a href="module_edit.html">Edit Module</a>
                  </li>
                </ul> <!-- /Sub menu -->
              </li>
              <li>
                <a href="help.html">
                  Help
                </a>
              </li>
            </ul>
          </div><!--/.nav-collapse -->
      </div>

      <div class="content center">
          <h1>Import Request
          <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False">
              <Columns>
                  <asp:BoundField DataField="Request_ID" HeaderText="Request_ID" SortExpression="Request_ID" />
                  <asp:BoundField DataField="Priority" HeaderText="Priority" SortExpression="Priority" />
                  <asp:BoundField DataField="Module_ID" HeaderText="Module_ID" SortExpression="Module_ID" />
              </Columns>


          </asp:GridView>

          </h1>
         <asp:Button ID="Button1" runat="server" Text="Import" 
              OnClick="Import_button_Click" style="height: 26px"/>


           </div>

         <div class="grid-100 footer">
        <p>Copyright © 2013 Team 3 Timetabling Support Website</p> 
      </div>

    </div> <!-- /container -->


      <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
          ConnectionString="<%$ ConnectionStrings:team03ConnectionString %>" 
          SelectCommand="SELECT * FROM [Archive]"></asp:SqlDataSource>
    <!-- Load JS here for greater good =============================-->
    <script src="js/jquery-1.8.2.min.js"></script>
    <script src="js/jquery-ui-1.10.0.custom.min.js"></script>
    <script src="js/jquery.dropkick-1.0.0.js"></script>
    <script src="js/custom_checkbox_and_radio.js"></script>
    <script src="js/custom_radio.js"></script>
    <script src="js/jquery.tagsinput.js"></script>
    <script src="js/bootstrap-tooltip.js"></script>
    <script src="js/jquery.placeholder.js"></script>
    <script src="http://vjs.zencdn.net/c/video.js"></script>
    <script src="js/application.js"></script>
    <!--[if lt IE 8]>
      <script src="js/icon-font-ie7.js"></script>
      <script src="js/icon-font-ie7-24.js"></script>
    <![endif]-->
      </form>
  </body>
</html>

C#: C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.VisualBasic.FileIO;
using System.Data.SqlClient;

namespace ImportPage
{

    public class CSVFile
    {

        public int Request_ID { get; set; }
        public int Priority { get; set; }
        public int Module_ID { get; set; }
        //...

    }


    public class CSV
    {


        public string GetConnectionString()
        { return System.Configuration.ConfigurationManager.ConnectionStrings["team03ConnectionString"].ConnectionString; }


        protected void Import_button_Click(object sender, EventArgs e)
        {
            //String request_ID2 = "";

            List<CSVFile> entries = new List<CSVFile>();

            using (TextFieldParser parser = new TextFieldParser(@"PreviousYear.txt"))
            {

                parser.TextFieldType = FieldType.Delimited;
                parser.Delimiters = new string[] { "," };
                string[] fields;

                while (!parser.EndOfData)
                {
                    fields = parser.ReadFields();
                    entries.Add(new CSVFile()
                    {
                        Request_ID = Convert.ToInt32(fields[0]),
                        Priority = Convert.ToInt32(fields[1]),
                        Module_ID = Convert.ToInt32(fields[2])
                        //...

                    });
                }

            }





            using (SqlConnection conn = new SqlConnection(GetConnectionString()))
            {


                string sql = "Insert INTO Requests (Priority, Module_ID) OUTPUT INSERTED.Request_ID VALUES (@Priority, @Module_ID)";

                try
                {

                    conn.Open();

                    foreach (CSVFile entry in entries)
                    {

                        using (SqlCommand cmd = new SqlCommand(sql, conn))
                        {

                            cmd.Parameters.AddWithValue("@Priority", entry.Priority);
                            cmd.Parameters.AddWithValue("@Module_ID", entry.Module_ID);

                            // ...
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    string msg = "Insert Error:";
                    msg += ex.Message;
                    throw new Exception(msg);
                }
                catch (FormatException ee)
                {
                    System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
                }
                catch (System.Exception eeee)
                {
                    System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");
                }
            }
        }
    }
}        

Thanks in advance. 提前致谢。 Any form of help would be greatly appreciated. 任何形式的帮助将不胜感激。

Looks like you are on the right track. 看来您走在正确的轨道上。 The Import button looks to be wired up to the empty Import_button_Click method in the .aspx page when it should be wired up to the Import_button_Click method in the CSV class. 当应该将导入按钮连接到CSV类中的Import_button_Click方法时,它看上去将连接到.aspx页中的空Import_button_Click方法。 Since the first method is empty, nothing happens. 由于第一种方法为空,因此什么也没有发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM