.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Sql Insert in my code behind is inserting extra spaces

Posted By:      Posted Date: October 25, 2010    Points: 0   Category :ASP.Net

Hi Folks

I have a insert inserting some stuff and for some odd reason 2 of my columns are getting inserted with extra spaces.

I have the strings .trim() but its not triming the insert. Oddly enough I am creating a directory on the fly using one of my same strings and its not creating the extra spaces when it does that.

 String UserName = User.Identity.Name.Trim();
                String OrgName = LabelOrg.Text.Trim();
                String path = Server.MapPath("~/Uploads/Documents/" + OrgName + "/" + DropDownList1.SelectedValue + "/" + DropDownListDocType.SelectedValue + "/");

cmd.CommandText = "INSERT INTO tblDocuments (coopcode, locationid, doctypecode, docname, dateuploaded, docstorename, username) VALUES('" + OrgName + "','" + DropDownList1.SelectedValue + "','" + DropDownListDocType.SelectedValue + "','" + FileUpload1.FileName + "','" + DateTime.Now + "','" + dateString + "-" + FileUpload1.FileName + "','" + UserName + "')";

The coopcode and locationid is the ones adding extra spaces. I am using OrgName for the coopcode 

Help :)

Thanks in advance

View Complete Post

More Related Resource Links

Automatically inserting server-side page events into C# when using code separation

I know this is a really basic question and I have spent the last half hour trying to find an answer so please forgive me if this has been asked before (it probably has)....When I create a web page with the C# code placed in a separate file I can't seem to easily add page events (apart from Page_Load). When I open the C# class code for the page all I see in the two drop-down boxes above the code is "Default" (with no other options in the drop-down) in the left-hand box and "ApplicationInstance,form1,Page_Load(object sender,EventArgs e),Profile" in the right hand box. I can't see a way to create the code for the other page events from either of these drop-downs.If I keep the C# code in the same file (i.e., not use code separation) everything works fine - I see "Server Objects & Events, Page, Form1, etc..." in the left hand drop-down and I can create new events in the right drop-down when either Page or Form1 are selected in the left box.Am I missing something really obvious?Many thanks for any suggestions

how to insert Value from C # code To SQL string?



I have connection string to sql and text Value wich I get from combobox no I wont to insert this Value to connection string how I do that correctly?

there is a code.

var value1 = CorporationCode1.Text;              

                DataSet ds2 = new DataSet();

                SqlConnection con2 = new SqlConnection("Data Source=DAN-PC;Initial Catalog=DMS_VEOLIA;Integrated Security=True");

how to insert Value from C # code To SQL string?



I have connection string to sql and text Value wich I get from combobox no I wont to insert this Value to connection string how I do that correctly?

there is a code.

var value1 = CorporationCode1.Text;              

                DataSet ds2 = new DataSet();

                SqlConnection con2 = new SqlConnection("Data Source=DAN-PC;Initial Catalog=DMS_VEOLIA;Integrated Security=True");

Insert on button event is inserting 2 records at a time


I have a form that is doing a simple insert, then a sub insert of a certain drop down selection is made. What i dont get is why the main insert is inserting duplicates and the sub works fine inserting 1 record per text as expected. I click the button 1 time, and when i check the table, there are 2 new records.. As you can see the insert is not wrapped with any conditions, once that is inserted i check if a slection was made and runs the sub insert.

My full code can be found in this post(http://forums.asp.net/t/1608619.aspx), but here is what i have for my button event.

    protected void btnSaveServConfig_Click(object sender, EventArgs e)   
        dac.insertServerConfigintosql(txtEmailLogin, txtEmailPass, Convert.ToInt32(ddlNumEmail.SelectedValue));   
            if (Convert.ToInt32(ddlNumEmail.SelectedValue) > 0)   
                 Dictionary<string, string> camValues = new Dictionary<string, string>();   
                    foreach (HtmlTableRow row in table1.Rows)   
                        foreach (HtmlTableCell cell in row.Cells)   
                            foreach (Control control in cell.Controls)   

C# Insert string from code behind to javascript function


Hi I am using the FullCalendar plugin and I am wanting to load events from the db to the page.

In my codebehind I have a string built up of the events which need to be included.

And I need it to be inserted into the javascript function in the position shown below:

Any help???

For example:

string Calevent = "{ title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29),url: 'http://google.com/'}";

$(document).ready(function() {
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        var calendar = $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'

Problem in inserting another entity via overriding insert method


I have problem to inserting another entity in overriding method of first entity my code sample is like bellow :

partial void InsertEntity1 ( Entity1 instance )


     Entity2 x = new Entity2() ;

tihs.Entity2s.Add(x) ;





in inserting Entity2 I get Exception "The Operation Cannot be perform for the entity because it is not being change track"


Insert spaces to get fixed length fields for flat file export



I have a query which extracts all the required data from a database and I need to load this data into a Text File. I am using a SSIS package to do this.

Now this file should have data in the format given below

437856785        A20101009This is construction         124728347

i.e the receiving file has no delimiters and each field is determined with a fixed length(fixed number of characters). The data I get out of my query for example for the first column returns just the value 437856785 and I need to append spaces to it to achieve the fixed length. I need to do to this kind of appending spaces to all the columns. Please suggest me ways to do this.

Thanks in advance..



SQL Update and Insert: Inserting a whole data table into another table



If I create a data tabe in C# like so:

datatable t = new DataTable;

DataColum C1 = new DataColum;//ID column


//the same with column C2

Then I fill up the table with some data.

Then the goal is to either insert this data or update data in an SQLtable in SQL. If the data is inserted, the ID column in t would be empty, if updated, it would not be. So in the insertion case, the sql query needs to make sure that unique IDs are assigned during insertion, in the update case, it just has to look for the right IDs.

How to go about this?

Asking because I am only familiar with updating and inserting single lines into a table. One could loop in C# over the datatable t of course and insert or update line by line, but this would probably be slow. Is there a way to write an SQL query like this somehow:

Insert Into SQLTable Values (@t)


And Update like this:

Update SQLTable SET ... Where C1 = @t.C1

Or something like that.

I know that SQL server can create automatic update and insert queries and that you can then type things in C# like


But, this has proven to be super slow on our server, for unknown reasons. I have asked on this forum and got some answers from experts, but was not able to srot out the problem.

How can we write

Upload and insert csv data into SQL from code behind


In my orginal post i asked the question to handle this within the .Net side.
I was trying to stay away from using SSIS package, and with help from another member, i was able to get the process to work with an excel spreadsheet.

But part of my project requires us to allow .csv files.. so my question is how can i modify the code i have now for the excel to work with a .csv file?
You can find the current code in my original post here: http://forums.asp.net/t/1584668.aspx

I not sure what the best solution is for the end result.. I was reading somewhere online that you can right the data from the file to a datalist or gridview so you can present the user with a view of what is being uploaded, then use that datacontrol to insert into SQL.

In my current code, im uploading the file, then using that file to do the insert. This works fine for .xls files.. but i need to accomplish the same thing for a .csv file.

Now not sure if we should force the file to include headers to make this easier or should we allow with and without and just validate before inserting so we can call the right code?


Data Access Inserting Code


We want to insert data  (ItemInserting) via the web page, then, bind the field content to the SQL database via ConnectionString. 

Go to the following Dynamic Data Site at http://cforedu.com/

What is the correct Data Access Code?

Here is the sample ItemInserting Code:

' FormView.ItemInserting Event
  Protected Sub Menu1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles Menu1.ItemInserting
    ' Get the connection string from Web.config. 
    ' When we use Using statement, 
    ' we don't need to explicitly dispose the object in the code, 
    ' the using statement takes care of it.
    Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("subscriberConnectionString").ToString())
      ' Create a command object.
      Dim cmd As New SqlCommand()

      ' Assign the connection to the command.
      cmd.Connection = conn

      ' Set the command text
      ' SQL statement or the name of the stored procedure. 
      cmd.CommandText = "INSERT INTO aspnet_Membership_FullAccess.subscriber(company, position, first, last, city, state, zip, phone, fax, email) VALUES (,,,,,,,,,)"


Code for insert command using C#, SQL, and ASP.NET


I'm having problems getting my code to work.  I have a couple text boxes.  When I hit the button I want it to insert the data from the two text boxes into the SQL database.  Could some show me some C# code that does this from something that actually works?   

"The data source control failed to execute the insert command." when inserting to sql table with tri



I have a data view web part that inserts a new record into a sql table. This works fine.

I have now needed to add a trigger to the sql table that sends an email when a new record is inserted (the code for which works fine) but now my insert fails with 'The data source control failed to execute the insert command.'.

If I disable the trigger the form works fine again.

Any ideas what could be causing this?


Strange problem, unable to insert single quote (already add in an extra single quote) for one partic

I have a very strange problem, I can update the table with single quote, but I cannot insert single quote. It only happen for this particular table in the database. Is there any suggestion on what I should look at?

I had already added in an extra single quote in my sql statement, something like this:

insert into Table_1 VALUES ('hello''s world','xxx')

how to access fields on a formview insert template from code behind


I want to access some fields from my formview insertmode.  I am in the code behind and it will not allow me to see them....


any help...


how to insert image into sql server manually (without code)

Can someone please tell me how to insert image into SQL server 2005 manually - without code.

I'm set the field as data type "image" and tried classical copy paste method, but without result.


Code Optimized Web Development Profile (VS 2010 and .NET 4.0 Series)

When you first run VS 2010 it prompts you to select an IDE profile to use. The profile you select will configure how tool windows are displayed/docked in the IDE by default and set the default keyboard shortcuts. You can then customize any of these settings by using the Tools->Options menu within the IDE and then override/change them. You can also later reset your profile and pick a different one by choosing the Tools->Import and Export Settings menu command.

Free Code Snippets - ASP.NET

You Can Find Useful ASP.NET Related Posts on the above link.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend