Converting string to int #2

hi all!

 is there a way to do that?

or a way to get the value of a dropdown list as an int?


do forgive my bad spelling
0
mestrebisli
4/4/2008 6:44:43 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

9 Replies
525 Views

Similar Articles

[PageSpeed] 52

Given a string variable s, use either

int i = Convert.ToInt32( s );

or

int i = Int32.Parse( s );

You can also use Int32.TryParse() as well.


Regards

Dave
0
DMW
4/4/2008 8:29:08 AM

Hi, use method Int32.Parse(string) or Int32.TryParse(string, out int).

For example:

int id = 0;

if (int.TryParse(Request.QueryString["id"], out id)
{
 // do something
}
else
{
 // fix problem
}

Have a nice day,

R.


rjicha
programmer + caffeine + taurine = new application
0
rjicha
4/4/2008 8:33:01 AM

mestrebisli :

 is there a way to do that?

or a way to get the value of a dropdown list as an int?


Yes you can using int.Parse or in.TryParse as suggest above.. Just be sure that your DDL.SelectedValue contains a numeric values.. see below 

if (DropDownList1.SelectedValue != "")
{
            int value = int.Parse(DropDownList1.SelectedValue);
}


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
4/4/2008 9:31:15 AM

 hi mestrebisli

you can convert DropDownList1.SelectValue to int by using following code, if the value for seleted item is integer than it works else it given a execption called Format Exception. 

        if (DropDownList1.SelectedValue != "")
        {
            Int32.Parse(DropDownList1.SelectedItem.Value);
        }

 Please Mark as Answer if post help you 


thanks n Regards
Amit
0
ar_amit1985
4/4/2008 9:56:12 AM

Try this... 

int i =  Convert.ToInt16(DropDownList1.SelectedItem.ToString());


Regards,
Punithkumar
0
Punithkumar
4/4/2008 10:38:20 AM

Hi,

you can. But look at the following example using textbox.

 

dim k as integer=0

Integer.tryparse(textbox1.text,k)

response.write(k)

 

Hope this will help you.

Thanks

Regards

Arshad

 

 


Please Mark as Answer if the post is helpful to you.
0
arshadtop
4/4/2008 10:46:14 AM

 yes, here a small sample

vb.aspx

 

<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
                <asp:ListItem Value="1">one</asp:ListItem>
                <asp:ListItem Value="2">two</asp:ListItem>
                <asp:ListItem Value="3">three</asp:ListItem>
                <asp:ListItem Value="4">four</asp:ListItem>
                <asp:ListItem Value="5">five</asp:ListItem>
                <asp:ListItem>six</asp:ListItem>
            </asp:DropDownList>
vb.aspx.vb 
  Protected Sub DropDownList2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList2.SelectedIndexChanged
        Dim test As Integer = 0
        Dim test2 As Integer = 0
        Try
            test = Convert.ToInt32(DropDownList2.SelectedValue.ToString())
        Catch
            Response.Write("<script language='javascript'>alert('" + DropDownList2.SelectedValue + " is not a valid number')</script>")
        End Try
        test2 = test + 10
        Response.Write("original selected value from dropdownlist is " + test.ToString() + ". after convert to Int then add 10: " + test2.ToString())

    End Sub
 c#.aspx
  <asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem Value="1">one</asp:ListItem>
<asp:ListItem Value="2">two</asp:ListItem>
<asp:ListItem Value="3">three</asp:ListItem>
<asp:ListItem Value="4">four</asp:ListItem>
<asp:ListItem Value="5">five</asp:ListItem>
<asp:ListItem>six</asp:ListItem>
</asp:DropDownList>
aspx.cs
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        int test = 0;
        try
        {
           test = Convert.ToInt32(DropDownList2.SelectedValue.ToString());
        }
        catch
        {
            Response.Write("&lt;script language='javascript'>alert('" + DropDownList2.SelectedValue + " is not a valid number')</script>");
        }
        int test2 = test + 10;
        Response.Write("original selected value from dropdownlist is " + test.ToString() + ". after convert to Int then add 10: " + test2.ToString());
    }
 
 
 
 
Bryian Tan
MCP, MCAD
0
BryianTan
4/4/2008 11:16:25 AM
tnx all! it worked!
do forgive my bad spelling
0
mestrebisli
4/4/2008 12:26:31 PM

mestrebisli:

hi all!

 is there a way to do that?

or a way to get the value of a dropdown list as an int?

 

int i = Convert.ToInt32( s );

or

int i = Int32.Parse( s );


Mark As Answer If my reply helped you.
0
syedwna
4/4/2008 1:58:36 PM
Reply:

Similar Artilces:

Converting classic to .NET 2 code, and .NET gets an error back from ADS?
 For future-proofing, our Internal Phone Directory is being moved onto our AD servers, and obviously we're using LDAP for queries.To get the phoneboook queries working, I adapted the current classic ASP code to use LDAP, and that works fine. However, we're wanting to move these pages to .NET, and that's where the problem comes in. Using the same basic logic from the Classic code (90% of its unchanged) to produce an LDAP query, I get the error  155 Unknown error (0x80005000)This is using the same website, and so the same credentials  - unless aspx pages run und...

How to convert Int to string and string to Int in Java Script
 How to convert Int to string and string to Int in Java Script 1:var strVar='23' ;var intVar=parseInt(strVar); any other method for this2:var intVar= 23;var strVar=intVar+''; any other method for this conversion please help me? thanks   Those methods work for what you need them to do.  Are you looking for alternatives?  I never lose, some people are just better than me at winning. 1: var strVar='23' ; var intVar=parseInt(strVar); any other method for this var intVar=strVar-0; var intVar=strVar*1; var intVar=strVar/1; var in...

convert string to int #2
Hi, i try to return cateogyid its integer type  but it shows the error Cannot implicitly convert type 'string' to 'int' i have send the coding step1  i have created procedure called addcategoryproc and i created class called categorycls to call the procedurepublic string addcat(string categorynames) {SqlConnection myconnection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);SqlCommand myCommand = new SqlCommand("addcategoryproc",myconnection); myCommand.CommandType = CommandType.StoredProcedure; myCommand.Param...

.net 3.5 convert to .net 2?
 how can i convert in Web Developer 2008 .net framework 3.5   to .net 2 ? KAHREDEN HAREKET ENGELLENNEMEZ  Hi,If you have not used any .NET 3.5 controls, you simply need to remove all references to .NET 3.5 within the web.config. I hope this helps, if it answers your question, don't forget to mark it as such for those who come afterwards.Regards,Gareth ChidgeyManaging DirectorPushInternet Ltd  ok.how  can i create new web site in web developer 2008 at .net framework 2  .    KAHREDEN HAREKET ENGELLENNEMEZ  try this http://we...

Why Visual Studio 2005 ask me to convert a solution already got converted Somebody did the conversion of a solution from .net 1.1 to .net 2.0 by using the automatic conversion wizard of Visual Stu
Why Visual Studio 2005 ask me to convert a solution already got converted Somebody did the conversion of a solution from .net 1.1 to .net 2.0 by using the automatic conversion wizard of Visual Studio 2005. Then, he changed to another company. Now, I take over his job. Unfortunately, when I attempted to open that solution, Visual Studio 2005 prompted me the conversion wizard again to forced me to perform a conversion on the solution. Does someone know why?--Harish Patel www.MicrosoftSQLandASP.netpatelharish@gmail.com Hi, How many projects are in the solution, does it have UNLOADE...

Is it possible to convert .do net 2 back to .net 1?
I have this application that runs fine on my pc, in which I run VS.Net 2005. When installed on a server with .Net Beta 2 a run time error referring to the line <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">in the web config file comes up. The server does not recognise that line of code, it seems to be still using .NET 1.Any ideas on how to fix that problem without installing VS.NET 2005 on the server?ThanksRaquel Install the .NET 2 beta 2 runtime on the server (if you can), then go into IIS  Manager and you should have a  ASP.NET  tab, w...

Differences between .net 1, .net 1.1, .net 2.0 and .net 3.0 #2
Hi, This seems to be a common question, but i havent got an answer yet:(Can, any one please explain me the differences between these versions.If you keep your feet firmly on the ground, you'll have trouble putting on your pants! There are too many differences for one email - - from 1.0 to 1.1 (not a whole lot of real change, other than fixes, at least compared to 1.1 to 2.0) With 2.0, there were many new declarative controls, with many new ideas added in With 3.0, it's a superset of 2.0 - instead of replacing the installation completely, it just 'added on' new functionality - I would...

Convert INT value to STRING so I can add it to another STRING
I'm trying to figure out how to convert an INT so that I can add it to another string in a statement likeSELECT '<a href="http://mydomain.com/' + [IntValue] + '">' + [LinkName]Where [IntValue] is an INT field containing a folder number.  I tried: TO_CHAR([IntValue, '999')but it didn't work. And I tried to find a TO_STRING function, but had no luck.Any advice to someone who is savy, but new to SQL Queries? SELECT '<a href="http://mydomain.com/' + STR([IntValue]) + '">' + [LinkName]HTHregardsASP.NET Hosting (HostingFest) Bingo!  I had to restrict the fu...

Getting error while converting string to double: Input string was not in correct format
Select Case LocalMeasuringUnitText Case "Currency" 'do the conversion hereDim ConversionRate As Double = GetConversionRate(_LanguageID)   Dim UKValue As Double 'String.Format("{0:c}", SelectedRow(rowloop).Item("TransData").ToString()) Dim varValue As Object = NothingDim Stringvalue As Object = SelectedRow(rowloop).Item("TransData").ToString.Trim 'varValue = Double.TryParse(Stringvalue, varValue) 'CType(Stringvalue, System.Double) 'UKValue = Convert.ToDouble(Stringvalue) / GetConversionRate(ConfigurationManager.AppS...

CrystalReportViewer problem after converting from .NET 1.1 to .NET 2.0
After converting my web aaplication project from .NET 1.1 to .NET 2.0, I am getting the following error when trying to run reports (and even in the VS 2005 designer):The base class includes the field 'crvBCSOnHandReport', but its type (CrystalDecisions.Web.CrystalReportViewer) is not compatible with the type of control (CrystalDecisions.Web.CrystalReportViewer)Has anybody else had this problem after converting?Thanks,Sacha...

Convert VB.Net to C# with C-Sharpener For VB 2.2
C-Sharpener For VB automatically converts VB.Net projects to C# projects through a Visual Studio Add-in. It has a simple to use Wizard interface and typically converts 99%+ of the VB.Net code. You can download a free trial version.We have just released version 2.2 which increases the trial size limit from 500 to 1000 lines of code. We have also improved handling of manifest files, long project paths, Visual Studio 2005 installation, and more.You can find out more athttp://www.elegancetech.com/csvb.aspxRoger JackPresidentElegance Technologies, Inc....

convert to string #2
i want to convert to string an integer value which i'm receving from database, in an SqlDataReader, how to do this?SHASHANK BHIDECAPGEMINI INDIA"THE ROAD TO SUCCESS IS ALWAYS UNDER CONSTRUCTION MARK MY RESPONSE AS ANSWER TO HELP ME BUILD IT :)"  you can use the toString() function.. for e.g. objreader["columnname"].toString() The real voyage of discovery consists not in making new landscapes, but in having new eyes shashankgwl:i want to convert to string an integer value which i'm receving from database, in an SqlDataReader, how to do this? Hi,...

Converting an int to a string
Hi I have an SQL Statement that will achieve a number from my Access database (it's a COUNT query) and I would like to show this as the text property of a label but understand that I have to convert it to a string first? Could anyone tell me how please ? many thanks. myInt.ToString should do it for you.JimMS MVP ASP.NET [VC++/MFC emeritus]Old Dog Learns New TricksPreferred programming language: cuneiform on clay tablets Hi, Thanks for that. Now I don't quite know how to get the figure for the count I want :-s Is this function correct? Function GetSuggestions() As System.D...

convert string to Int
I am trying to select data from a DB, but keep getting a missmatch error. I know why this is happening, but don't know how to fix it. Basically I have a form which takes in a string, in the DB the string is actually a number. How do I convert the string that was in the form to a number for the DB. EX: loginSQL = "UPDATE employees SET status = 'complete' WHERE id = "& Session("ID") Session("ID") is a string, but I want a number!!!! Thanks a alot! :) use sql function: cast(parameter as int). however, your sql string looks good. your ...

Web resources about - Converting string to int #2 - asp.net.getting-started

PastBook’s Filepicker.io Integration Eases Process Of Converting Facebook Content To Books
PastBook , one of several companies that allow Facebook users to publish their content on the social network in actual books , announced the ...

Facebook No Longer Converting Groups Into Pages
Back when Facebook first launched Facebook Pages, many businesses and brands who had built up substantial audiences in their Facebook Groups ...

Zwartz Laminating-Converting B.V. on the App Store on iTunes
Get Zwartz Laminating-Converting B.V. on the App Store. See screenshots and ratings, and read customer reviews.


"Occupier" Thanked Former Soviet Citizen for "Converting" Him to Capitalism, Pro-Israel, Pro-USA - YouTube ...
May Day Demonstration on Union Square in New York City Zionism & Birth of Modern Israel in 1948: Former Soviet Citizen Pays Tribute to Ben-Gurion ...

Click go fears of converting print files
Is there a way to convert a print queue item to a .RTF or .PDF file? I like to save or email them. - The Sydney Morning Herald

Sudanese woman ordered to hang under sharia law for converting to Christianity gives birth
Khartoum, Sudan: A Christian Sudanese woman sentenced to hang for apostasy has given birth in jail, a Western diplomat said on Tuesday.

Imams warn against radicalism to Aboriginal inmates converting to Islam
The prison system has enlisted the help of ASIO to crack down on radicalisation behind bars amid revelations that Aboriginals are converting ...

Converting the world's companies one by one - The Science Show - ABC Radio National (Australian Broadcasting ...
Image: Trucks carrying logs make their way up a road in Jambi, Indonesia. A vast area of the Sumatran forest, and orangutan habitat, is being ...

Converting Churches Into Homes Is The Latest Hollywood Trend
You don't have to be a believer to be moved by the beauty of a church.

Resources last updated: 12/3/2015 1:25:30 PM