tags:

views:

4328

answers:

3

Hi all,

I am fairly new to c# and asp.net and am having an issue converting type;

My situation is that I have a search engine that has a textbox for the search text and two radio buttons for the search location ( IE City1 or City2 )

When I recieve the search text and radio buttons they are in the form of a string IE

string thesearchtext, thecitytype;
thesearchtext = HttpContext.Current.Request.QueryString["s"].ToString();
thecitytype = HttpContext.Current.Request.QueryString["bt"].ToString();

When I recieve the cities radiobutton they will be in the format of "city1" or "city2".

What i need to do is convert the city radiobuttons into an int so that I can use them in my search dataset. IE I need to convert "city" to "1" and "city2" to "2".

I understand this is probably a simple type conversion however I just cannot figure it out. I tried an "if" statement to convert the cities but I keep getting:

cannot implicitly convert type 'string' to 'bool'

I was trying code like this:

int listingsToSearch;
if (thecitytype = "City1")
{
    listingsToSearch = Convert.ToInt32(1);
}
else
{
    listingsToSearch = Convert.ToInt32(2);
}

Any help in guiding me in the right direction would be greatly appreciated Thanks...

+5  A: 

try: c# equality operator == not =

if (thecitytype == "City1")
Rick Hochstetler
Thanks Rick for your knowledge, that worked great.
Jason
+1  A: 

Also just

listingsToSearch = 1;

will work. No need to convert 1 to an int. It's already an int.

Thanks freelookenstein
Jason
A: 

Here is some code in you can use with NUnit that demonstrates another technique for calculating listingToSearch - You will also notice that with this technique, you won't need to add extract if/else, etc as you add more cities - the test below demonstrates that the code will just try to read integer starting after "City" in the radio button label. Also, see the very bottom for what you could write in your main code

[Test]
public void testGetCityToSearch()
{

    // if thecitytype = "City1", listingToSearch = 1
    // if thecitytype = "City2", listingToSearch = 2

    doParseCity(1, "City1");
    doParseCity(2, "City2");
    doParseCity(20, "City20");        
}

public void doParseCity(int expected, string input )
{
    int listingsToSearch;
    string cityNum = input.Substring(4);
    bool parseResult = Int32.TryParse(cityNum, out listingsToSearch);
    Assert.IsTrue(parseResult);
    Assert.AreEqual(expected, listingsToSearch);
}

In your regular code you can just write:

string thecitytype20 = "City20";
string cityNum20 = thecitytype20.Substring(4);
bool parseResult20 = Int32.TryParse(cityNum20, out listingsToSearch);
// parseResult20 tells you whether parse succeeded, listingsToSearch will give you 20
dplante