0

I am trying to add data rows into a data table created using Visual Studio GUI. I have a code to do this but when code execution is finished I can't see any data in datatable using Show Table Data. What is wrong with it?

Database design:

enter image description here

Code to insert data from text file:

SqlConnection sqlConn;
    string connectionString = EasyPopulatio.Properties.Settings.Default.PhonesConnectionString;
    public DataHelper()
    {
        sqlConn = new SqlConnection(connectionString);
    }
    public void ImportText(string path)
    {
        sqlConn.Open();
        string[] data = File.ReadAllLines(path);
        string query = "INSERT INTO dbo.Table1 (GSMNO) VALUES (@gsmno)";
        using (SqlCommand cmd = new SqlCommand(query, sqlConn))

        foreach (string item in data)
        {
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@gsmno", SqlDbType.VarChar).Value = item;
            cmd.ExecuteNonQuery();
        }

        sqlConn.Close();
    }
Ali Tor
  • 2,772
  • 2
  • 27
  • 58
  • 2
    What is the connection string used to work in code with the database and what is the connection string used to show data using the Server Explorer? – Steve Mar 19 '17 at 17:05
  • [Check this answer](http://stackoverflow.com/questions/17147249/why-saving-changes-to-a-database-fails/17147460#17147460) to see if you are in the same condition. – Steve Mar 19 '17 at 17:07
  • 2
    By the way, the code above can work only if you have only one item int the data array. The second loop should fail because you readd another parameter, (Of course you don't use { .... } around the VALUES section but ( .... ) – Steve Mar 19 '17 at 17:11
  • @Steve `connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Phones.mdf;Integrated Security=True"`. Also I took a look at the script to show table content and it was empty. So I wrote `select * from Table1` and executed it but then `0 rows affected` message appeared, so it was empty again. What is the problem? – Ali Tor Mar 19 '17 at 17:19
  • 1
    I have pointed you to an answer where the problem relative to the use of DataDirectory substitution string is explained. You should change the property Copy to the output directory of the MDF file to Copy if Newer and add a new connection to your Server Explorer window that points to the MDF in the BIN\DEBUG folder. – Steve Mar 19 '17 at 17:22
  • 1
    Ok I have changed SqlConnection string to `BIN\DEBUG\Phones.mdf` and it worked. Thanks. – Ali Tor Mar 19 '17 at 17:40

0 Answers0