0

I have a listbox with items that are a concatenation of two columns (Game_ID+"- "+Name) in a different listbox. So each listbox item looks like:

1- Game#1

2- Game#2

...

...

10- Game#10

...

100- Game#100

I need to know how to make the parameter only the game_ID portion of the list item. So basically I need just the portion to the left of the hyphen.

    string newPGame = "INSERT INTO admin.promo_games(promo_ID, Game_ID) VALUES(@PID, @GameID)"
    SqlCommand insGames = new SqlCommand(newPGame, misc);

    insGames.Parameters.AddWithValue("@PID", txtID.Text);
    insGames.Parameters.AddWithValue("@GameID", lstSelGames.SelectedValue);
       foreach (string item in lstSelGames.Items)
          {
             insGames.ExecuteNonQuery();
          }
2
  • 2
    Why not have the SelectedValue (the behind scenes value) of the select list just be that value, so when you get it from the form, it is what you need. The display text can be whatever you want and then you dont have to parse it. Commented Sep 17, 2018 at 19:32
  • 1
    You may want to stop using AddWithValue. Also SqlCommand is IDisposable so should be in a using block. Commented Sep 17, 2018 at 19:48

1 Answer 1

2

You can use Substring and int.Parse to parse the number:

var itemText = lstSelGames.SelectedValue.ToString();
var numberString = itemText.Substring( itemText.IndexOf("-") );
var number = int.Parse(numberString);

A better solution would be to create a class that represents an item in the list and then use a strongly typed instance here:

public class Game
{
    public int Id {get;set;}
    public string Name {get;set;}

    public override string ToString()
    {
       return Id + Name;
    }
}

Then SelectedValue will actually be of type Game:

var game = (Game)lstSelGames.SelectedValue;
//use game.Id
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.