Click here to Skip to main content
15,895,815 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:


C#
if (this.DataCenterLaborFileUpload.HasFile)
            {
                var extension = Path.GetExtension(DataCenterLaborFileUpload.FileName);
                string currentName = "";
                decimal currentHours = 0.00M;
                decimal currentFTE = 0.00M;
                string ResourceName = "";
                
                if (extension == ".csv")
                {
                    StreamReader csvreader = new StreamReader(DataCenterLaborFileUpload.FileContent);
                    DataTable dt = new DataTable();
                    dt.Columns.Add("txtName");
                    dt.Columns.Add("txtHours");
                    dt.Columns.Add("txtFTE");

                    while (!csvreader.EndOfStream)
                    {
                        DataRow dr = dt.NewRow();
                       
                        var line = csvreader.ReadLine();
                        var values = line.Split(',');

                        if (values[0].Trim() != "Pers.No.")
                        {
                            SqlCommand cmd = new SqlCommand("SELECT ResourceName FROM StaffTracking where PersonnelResourceType  = 'Supplier' order by PersonnelResourceType, ResourceName");
                            cmd.Connection = conn;
                            conn.Open();                         
                            if (ResourceName == (values[1].Trim()))
                            {
                                
                            
                                if (values[1].Trim() == currentName)
                                {

                                    currentHours = currentHours + Convert.ToDecimal(values[9].Trim());

                                }
                                else
                                {
                                    if (currentName != "")
                                    {
                                        dr["txtName"] = currentName;
                                        dr["txtHours"] = currentHours;
                                        dr["txtFTE"] = currentFTE + Math.Round(currentHours / (weekdaysInMonth() * 8), 2);

                                        dt.Rows.Add(dr);
                                        dt.AcceptChanges();
                                       
                                    }

                                    currentHours = Convert.ToDecimal(values[9].Trim());
                                    currentName = values[1].Trim();
                                }

                            }
                              
                        }
                        
                    }
                    
                    DataRow drfinal2 = dt.NewRow();
                    drfinal2["txtName"] = currentName;
                    drfinal2["txtHours"] = currentHours;
                    drfinal2["txtFTE"] = currentFTE + currentHours / (weekdaysInMonth() * 8);
                    dt.Rows.Add(drfinal2);
                    dt.AcceptChanges();


                    gvDataCenterLabor.DataSource = dt;

                }
                conn.Close();

                gvDataCenterLabor.DataBind();
               
                //     Page.DataBind();
            }
            
            
        }
Posted
Updated 28-Mar-15 11:39am
v4
Comments
Sascha Lefèvre 28-Mar-15 16:56pm    
If you want a helpful answer you should provide an explanation of your problem and not just throw your code at us.
Norris Chappell 28-Mar-15 17:15pm    
Sorry it says I only have 20-200 characters. My issue is that I can't seen to get the datagridview to show only the first record in my csv file. It must loop through the csv adding the hours then proceed to the record person. It they are not a supplier then skip that person and go to the next person. If I take out my select statement it writes out both suppliers and others.
Sascha Lefèvre 28-Mar-15 17:31pm    
"Sorry it says I only have 20-200 characters." - I think that's just for the title. I don't know if there's a restriction for the body of the post but you're nowhere near it :)

I would suggest: Use the "Improve question"-Link at the bottom of your question to edit it and 1) include a sample csv file (or a meaningful excerpt) and 2) your above comment in a slightly more detailed form. I have some rough idea what you want but not really. What I can tell you right away though: Your database connection doesn't do anything. Are you aware of that?
Norris Chappell 28-Mar-15 17:33pm    
Sascha, I am not sure where to put the loop of the sql server table in my code. That is my issue. Thank you for any suggestions.
Sascha Lefèvre 28-Mar-15 17:54pm    
I can't tell you without seeing your csv..

I don't know if your code will work 100% after you apply this but at least it will solve the issue reading from the database.

A sample database-access (for SQL-Server), from opening the connection to reading all the records, applying good practices (using-Blocks, Sql-Parameters and abstract Db*****-baseclasses instead of database-specific classes):

C#
using (DbConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
 
    using (DbCommand cmd = conn.CreateCommand())
    {
        cmd.Connection = conn;
        cmd.CommandText = "SELECT col1, col2 FROM table1 WHERE col3 = @p1;";
        // let's assume col1 is an int (Int32); col2 and col3 a nvarchar (String)

        DbParameter p1 = cmd.CreateParameter();
        p1.ParameterName = "p1";
        p1.Value = "something";

        cmd.Parameters.Add(p1);
 
        using (DbDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read()) // loops through all result records
            {
                int col1 = dr.GetInt32(0);
                string col2 = dr.GetString(1);

                // do something with col1 and col2 here
            }
        } // the datareader will be closed and disposed here
    } // the command will be disposed here
} // the connection will be closed and disposed here


Edit after comment:

Sql-Parameters are the best way to "communicate" your query-constraints to the database. In your case, instead of this:
SQL
SELECT ResourceName FROM StaffTracking where PersonnelResourceType  = 'Supplier' order by PersonnelResourceType, ResourceName

you could write this:
SQL
SELECT ResourceName FROM StaffTracking where PersonnelResourceType = @restype order by PersonnelResourceType, ResourceName

and create an Sql-Parameter (in this case named "restype") that carries the desired value (in this case "Supplier") and append it to the Parameter-Collection of the Sql-Command:
C#
DbParameter p1 = cmd.CreateParameter();
p1.ParameterName = "restype";
p1.Value = "Supplier";
cmd.Parameters.Add(p1);

Think of it like some sort of variable for SQL-commands. SQL-Server takes your query-string and replaces all occurrences of those Parameter-Names (starting with an @) by the value that you assigned to the Sql-Parameter-Object with the same name.

It is "the best way" because:
- If you develop an application that stores input from strangers (e.g. website-visitors) into your database, you avoid the risk of SQL-Injection-Attacks[^]
- It is better maintainable because your query-string is easily readable
- In case of string-values you avoid potential SQL-syntax errors in case the string contains quotes

Edit 2:

The last two points don't directly apply to your previous code but very often you see people constructing their query-strings like this:
C#
string query = "SELECT col1 FROM table1 WHERE col2 = '" + someVariable + "' AND col3 = '" someOtherVariable "'";
 
Share this answer
 
v3
Comments
Norris Chappell 28-Mar-15 19:12pm    
Replace SELECT col1, col2 FROM table1 WHERE col3 = @p1 with
SELECT ResourceName FROM StaffTracking where PersonnelResourceType = 'Supplier' order by PersonnelResourceType, ResourceName

I don't understand this part?
DbParameter p1 = cmd.CreateParameter();
p1.ParameterName = "p1"; What goes here?
p1.Value = "something"; What goes here?
Norris Chappell 28-Mar-15 19:20pm    
p1.ParameterName = "PersonnelResourceType";
p1.Value = "Supplier";

cmd.Parameters.Add(p1); Why add?
Is this code a replacement for my while statement?
Sascha Lefèvre 28-Mar-15 19:33pm    
I updated the solution, please take a look.

> cmd.Parameters.Add(p1); Why add?
> Is this code a replacement for my while statement?

The Sql-Parameter needs to be "transported" to the database-server - for that to happen it must be added to the Parameter-Collection of the Sql-Command.
Sascha Lefèvre 28-Mar-15 19:39pm    
Edited a second time.
Norris Chappell 28-Mar-15 20:29pm    
using (DbConnection conn = new SqlConnection(connectionString))
{
conn.Open();

using (DbCommand cmd = conn.CreateCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT ResourceName FROM StaffTracking where PersonnelResourceType = @restype order by PersonnelResourceType, ResourceName";
DbParameter p1 = cmd.CreateParameter();
p1.ParameterName = "restype";
p1.Value = "Supplier";
cmd.Parameters.Add(p1);

using (DbDataReader dr = cmd.ExecuteReader())
{
while (dr.Reader())
{

}
}
}
}

I getting errors:
Error 2 The type or namespace name 'DbConnection' could not be found (are you missing a using directive or an assembly reference?) C:\Users\pzd74f\Downloads\SharePointProjects\SharePointProjects\StaffingWebParts\StaffingWebParts\ImportDataCenterandCATWData\ImportDataCenterandCATWDataUserControl.ascx.cs 176 36 StaffingWebParts
Error 3 The name 'connectionString' does not exist in the current context C:\Users\pzd74f\Downloads\SharePointProjects\SharePointProjects\StaffingWebParts\StaffingWebParts\ImportDataCenterandCATWData\ImportDataCenterandCATWDataUserControl.ascx.cs 176 74 StaffingWebParts
Error 4 The type or namespace name 'DbCommand' could not be found (are you missing a using directive or an assembly reference?) C:\Users\pzd74f\Downloads\SharePointProjects\SharePointProjects\StaffingWebParts\StaffingWebParts\ImportDataCenterandCATWData\ImportDataCenterandCATWDataUserControl.ascx.cs 180 40 StaffingWebParts
Error 5 The type or namespace name 'DbParameter' could not be found (are you missing a using directive or an assembly reference?) C:\Users\pzd74f\Downloads\SharePointProjects\SharePointProjects\StaffingWebParts\StaffingWebParts\ImportDataCenterandCATWData\ImportDataCenterandCATWDataUserControl.ascx.cs 184 37 StaffingWebParts
Error 6 The type or namespace name 'DbDataReader' could not be found (are you missing a using directive or an assembly reference?) C:\Users\pzd74f\Downloads\SharePointProjects\SharePointProjects\StaffingWebParts\StaffingWebParts\ImportDataCenterandCATWData\ImportDataCenterandCATWDataUserControl.ascx.cs 189 44 StaffingWebParts
Error 7 A local variable named 'dr' cannot be declared in this scope because it would give a different meaning to 'dr', which is already used in a 'parent or current' scope to denote something else C:\Users\pzd74f\Downloads\SharePointProjects\SharePointProjects\StaffingWebParts\StaffingWebParts\ImportDataCenterandCATWData\ImportDataCenterandCATWDataUserControl.ascx.cs 189 57 StaffingWebParts

Am I missing something else?
C#
if (this.DataCenterLaborFileUpload.HasFile)
            {
                var extension = Path.GetExtension(DataCenterLaborFileUpload.FileName);
                string currentName = "";
                decimal currentHours = 0.00M;
                decimal currentFTE = 0.00M;
                string ResourceName = "";
                
                if (extension == ".csv")
                {
                    StreamReader csvreader = new StreamReader(DataCenterLaborFileUpload.FileContent);
                    DataTable dt = new DataTable();
                    dt.Columns.Add("txtName");
                    dt.Columns.Add("txtHours");
                    dt.Columns.Add("txtFTE");

                    while (!csvreader.EndOfStream)
                    {
                        DataRow dr = dt.NewRow();
                       
                        var line = csvreader.ReadLine();
                        var values = line.Split(',');

                        if (values[0].Trim() != "Pers.No.")
                        {
                            using (DbConnection conn = new SqlConnection("SQLStaffingConn"))

                            {
                                conn.Open();

                                using (DbCommand cmd = conn.CreateCommand())
                                {
                                    cmd.Connection = conn;
                                    cmd.CommandText = "SELECT ResourceName FROM StaffTracking where PersonnelResourceType  = @restype order by PersonnelResourceType, ResourceName";
                                    DbParameter p1 = cmd.CreateParameter();
                                    p1.ParameterName = "restype";
                                    p1.Value = "Supplier";
                                    cmd.Parameters.Add(p1);

                                    using (DbDataReader row = cmd.ExecuteReader())
                                    {
                                        while (row.Read())
                                        {
                                            string col2  = row.GetString(1);
                                        }
                                    }
                                }
                            }
                               if  (ResourceName == (values[1].Trim()))
                               {
                                
                            
                                if (values[1].Trim() == currentName)
                                {

                                    currentHours = currentHours + Convert.ToDecimal(values[9].Trim());

                                }
                                else
                                {
                                    if (currentName != "")
                                    {
                                        dr["txtName"] = currentName;
                                        dr["txtHours"] = currentHours;
                                        dr["txtFTE"] = currentFTE + Math.Round(currentHours / (weekdaysInMonth() * 8), 2);

                                        dt.Rows.Add(dr);
                                        dt.AcceptChanges();
                                       
                                    }

                                    currentHours = Convert.ToDecimal(values[9].Trim());
                                    currentName = values[1].Trim();
                                }

                            }
                               
                        }
                         
                    }
                    
                    DataRow drfinal2 = dt.NewRow();
                    drfinal2["txtName"] = currentName;
                    drfinal2["txtHours"] = currentHours;
                    drfinal2["txtFTE"] = currentFTE + currentHours / (weekdaysInMonth() * 8);
                    dt.Rows.Add(drfinal2);
                    dt.AcceptChanges();


                    gvDataCenterLabor.DataSource = dt;

                }
                

                gvDataCenterLabor.DataBind();
               
                //     Page.DataBind();
            }
            
            
        }
 
Share this answer
 
Comments
Norris Chappell 28-Mar-15 21:30pm    
Sorry. I didn't understand what you were saying. I want to thank you for all of your help. I have been working on this for quite awhile.
Sascha Lefèvre 28-Mar-15 22:00pm    
You're welcome!

You want to read ResourceName from the database-query-result into your variable "ResourceName", right? Then instead of

string col2 = row.GetString(1);

you have to write

ResourceName = row.GetString(0);

and you need to move all the code that should use the variable "ResourceName" into the loop below that line, otherwise, like your code looks currently, "ResourceName" will have only the value of the very last result record (see my 3rd last comment).
Norris Chappell 28-Mar-15 21:58pm    
Removing the quotes gives me errors.
Sascha Lefèvre 28-Mar-15 22:04pm    
In your original post it is not visible where your SqlConnection-Object "conn" is being created. Wherever you do that you should have some kind of connection string (!?) - otherwise please post the code-part where you (originally) created the "conn" object.
Norris Chappell 28-Mar-15 22:43pm    
public SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLStaffingConn"].ConnectionString);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900