locked
Error - Start Index cannot be less than 0 RRS feed

  • Question

  • User-1499457942 posted

    Hi

      On the below code i get above error . I want to save data like this (Mah,Raj,Del,) . If there is comma in the end it should be removed.

      cmd.Parameters.AddWithValue("@Location", SqlDbType.VarChar).Value = strLocation.Remove(strLocation.LastIndexOf(","));

    Thanks

    Sunday, August 26, 2018 3:34 PM

Answers

  • User409696431 posted

    You are not considering the case where there is no "," in the strLocation.   If there is not, LastIndexOf returns -1, and you can't String.Remove at index position -1.

    Check for a trailing comma first, then remove it if it is there.  You can use TrimEnd(',') to do this.  (It will remove a trailing comma, and, in fact, if there are more than one trailing commas, it will remove all of them)

    Try:

    cmd.Parameters.AddWithValue("@Location", SqlDbType.VarChar).Value = strLocation.TrimEnd(",");

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, August 26, 2018 5:11 PM

All replies

  • User409696431 posted

    You are not considering the case where there is no "," in the strLocation.   If there is not, LastIndexOf returns -1, and you can't String.Remove at index position -1.

    Check for a trailing comma first, then remove it if it is there.  You can use TrimEnd(',') to do this.  (It will remove a trailing comma, and, in fact, if there are more than one trailing commas, it will remove all of them)

    Try:

    cmd.Parameters.AddWithValue("@Location", SqlDbType.VarChar).Value = strLocation.TrimEnd(",");

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, August 26, 2018 5:11 PM
  • User-1499457942 posted

    Hi

      I have written like below but it is giving error -  string.trimend has some invalid arguments

    cmd.Parameters.AddWithValue("@Location", SqlDbType.VarChar).Value = strLocation.TrimEnd(",");

    Thanks

    Sunday, August 26, 2018 5:17 PM
  • User-1499457942 posted

    Hi

      Resolved . strLocation.TrimEnd(',');

    Thanks

    Sunday, August 26, 2018 5:18 PM