-4

I got a string wich contains a " \ ", but i want to remove it. simply using

string.Replace(@"\", "");

doesnt work. Heres the string:

'Samsung Monitor 21\" ' 

Should be:

'Samsung Monitor 21" ' 

Ok then let me go in Detail.

Iam working with postgresql databases. My testdatabase contains some products, eg. -> Samsung Monitor 21" <-(im a bit afraid of using ' and " ) My Programm logs into the Database, reads a Table and puts it into a Datatable. Now i want to edit the table by using the CellEdit Event. I'am constucting a string that gets run as a command by the query. Since I have no vertain Keyword, that is not allowed to be changed, I have to compare every other value of that Row to the Rows in my Database.

"UPDATE artikel SET warengruppe = 5 WHERE artikel_nr = '1100pplus' AND
bezeichnung = 'Samsung Monitor 21\" ' AND lieferanten_nr = 134 AND 
mengeneinheit = 'ST' AND verkaufspreis = '775.00' AND einkaufspreis 
= '465.00' AND lieferzeit = 28 AND bestand_lager = 2 AND bestand_minimum = 
10 AND jahresumsatz = '1550.00' AND vorjahresumsatz = '2325.00'"

Since every Value is taken out of the Datagrids Cells, it automaticly puts the Backslash infront of the -> " <-. And I do need that to compare it in my SQLCommand.

but just giving that string like it is, it obvioulsy doesnt work, because my DataBase has

'Samsung Monitor 21" '

and not

'Samsung Monitor 21\" '

And just using "LIKE" is to much of a Workaround..

And just for the ones asking, here is my complete Method:

private void SQLDatagrid_OnCurrentCellChanged(object sender, DataGridCellEditEndingEventArgs e) {

        DataGridColumn col1 = e.Column;
        DataGridRow row1 = e.Row;
        int row_index = ((DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1);
        int col_index = col1.DisplayIndex;
        int i = 0;
        string commandstring = "UPDATE artikel SET ";
        string tmpcell = dt.Rows[row_index][col_index].ToString();
        tmpcell = tmpcell.Replace(',', '.');
        bool valueisint = isInteger(tmpcell);

        commandstring += dt.Columns[col_index].ColumnName + " = ";

        if (!valueisint)
        {
            commandstring += "'";
        }
        commandstring += tmpcell;
        if (!valueisint)
        {
            commandstring += "'";
        }
        commandstring += " WHERE ";

        foreach (DataColumn dataColumn in dt.Columns)
        {
            string cell = dt.Rows[row_index][i].ToString();
            cell = cell.Replace(',', '.');
            bool tmp = isInteger(cell);
            if (i > 0 && i != col_index)
            {
                commandstring += " AND ";
            }
            if (i != col_index)
            {
                commandstring += dataColumn.ColumnName + " = ";
                if (!tmp)
                {
                    commandstring += "'";
                }
                commandstring += cell;
                if (!tmp)
                {
                    commandstring += "'";
                }
            }
            i++;
        }
        commandstring = Regex.Replace(commandstring, @"\\", ""); // this is just trying out
        commandstring = commandstring.Replace(@"/", "");  // As is this
        SqlCommand command = new SqlCommand(commandstring);
nuuse
  • 109
  • 1
  • 11
  • 3
    `string str = "'Samsung Monitor 21\\\"'"; str = str.Replace("\\", "");` – Tim Schmelter Oct 24 '17 at 09:53
  • Just add one backslash to escape (`\\`): `string.Replace("\\", "");`. – Tetsuya Yamamoto Oct 24 '17 at 09:54
  • 1
    I'll bet you don't have a string with `\ `. You have a string with **"** – Panagiotis Kanavos Oct 24 '17 at 09:54
  • Is it just me or does this question come up at least once a week? – Manfred Radlwimmer Oct 24 '17 at 09:59
  • I dont udnerstand why yall downvote. The string is generated by the Programm, so i cannot edit that. And ofc, the \ is escaping the ", but still, i want to remove that.. – nuuse Oct 24 '17 at 10:00
  • @Joschka Read the question I linked. – Manfred Radlwimmer Oct 24 '17 at 10:00
  • @Joschka where did you find this string and why do you think it contains a backslash? Did you see this in the *watch window* or *debugger tooltip* perhaps? `\" ` is *precisely* how you insert a double quote into a string. – Panagiotis Kanavos Oct 24 '17 at 10:05
  • @Joschka you'll have to provide code that actually reproduces a bug. Code that sets a string value to a variable and performs a replacement. What you typed doesn't show anything. – Panagiotis Kanavos Oct 24 '17 at 10:08
  • `but still, i want to remove that` there's **nothing** to remove. Your string does *not* contain any backslash. That's how the watch window always displayed strings, how developers always expected it to behave: the same as their code. Otherwise, tabs, newlines and non-space separators would be invisible. Check the screenshot in my answer. – Panagiotis Kanavos Oct 24 '17 at 10:19
  • @Joschka Google for `Bobby Tables`. Your string still doesn't contain any backslashes but you have a SQL injection vulnerability. If even one of those parameters contains a **single** quote, the query is invalid. Worse, if one of the values is, eg `'; DELETE FROM artikel;--` you'll lose all data. That's how SQL injection attacks happen. You should use parameterized queries instead of construnting queries by hand – Panagiotis Kanavos Oct 24 '17 at 13:10
  • @Joschka In fact, if you have a *DataTable* why are you constructing the query yourself instead of using a DbDataAdapter? A single call to [DbDataAdapter.Update(DataTable)](https://msdn.microsoft.com/en-us/library/z1z2bkx2(v=vs.110).aspx) will find the changed values and execute the updates – Panagiotis Kanavos Oct 24 '17 at 13:12
  • @Joschka anyway, if you insist, enter `commandstring,nq` as a watch variable, as I show in my answer. What do you see? I bet it's `UPDATE artikel SET warengruppe = 5 WHERE artikel_nr = '1100pplus' AND bezeichnung = 'Samsung Monitor 21" ' AND lieferanten_nr = 134 AND mengeneinheit = 'ST' AND verkaufspreis = '775.00' AND einkaufspreis = '465.00' AND lieferzeit = 28 AND bestand_lager = 2 AND bestand_minimum = 10 AND jahresumsatz = '1550.00' AND vorjahresumsatz = '2325.00'` – Panagiotis Kanavos Oct 24 '17 at 13:16
  • @PanagiotisKanavos I did not know about DbDataAdapter, thank you for your help – nuuse Oct 24 '17 at 13:27
  • PS notice the trailing space after `"`? If the database *doesn't* have the same trailing space, the update will fail. I also noticed that you replace `,` with `.`. Are you trying to fixed a failed decimal conversion to text? You wouldn't even have a conversion if you used parameterized queries and passed numbers as numeric parameters. You *can't* cover this up either, because *thousand* separators will result in an invalid string again, eg `1.000.00`. – Panagiotis Kanavos Oct 24 '17 at 13:28
  • @Joschka I suggest you find a tutorial instead of trying code at random. This is the oldest data access technique in .NET, available since 2002. There's even a DataSet Designer that allows you to specify the columns and generate the classes. Check [this walkthrough from the documentation itself](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/populating-a-dataset-from-a-dataadapter) – Panagiotis Kanavos Oct 24 '17 at 13:31

1 Answers1

1

You don't have to do anything. You don't have a string with a \. You have a string with a " only. The debugger and watch windows display the string in the form used by string literals in almost all languages (C#, VB.NET, Java, Javascript, PHP, Ruby), ie with a \ in front of it.

Your string is Samsung Monitor 21". In order to type this into code though, you'd have to write :

var myString = "Samsung Monitor 21\" ";

NOTE

You can force the watch window to display the string without quotes if you add the nq format specifier to the watch expression, eg myString,nq

BackslashAndNQ

This shows that the double quote is escaped in the normal watch expression, unescaped if ,nq is added

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236