Showing posts with label convert. Show all posts
Showing posts with label convert. Show all posts

Saturday, March 31, 2012

String to Base64

Hi,

I need to convert an ASCII string to Base64 encoding in VB .NET. All of the references I have found show how to convert a binary data stream to Base64, but I only need to convert a text string. What is the simplest way to do this?

Hi,

It is always advisable to convert to binary first before performing encoding or encrypting operations. You can convert the string to binary and then encode to Base64.

Hope this helps,

Vivek

string to byte array conversion

I've a string similiar to "A509DE5B" (Length == 8 ) where each 2 characters are 1 hex number. How to convert such string into array of bytes (Lenght == 4)? In C# please, it's important...Byte.Parse()?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystembyteclassparsetopic.asp
Hi LesioS!

I think you should try out something like this (I haven't tested it out myself, not sure if it works!!)


string sBytes = "A509DE5B";

Byte[] bytes = new Byte[(int)(sBytes.Length/2)];

int i = 0, j = 0;

while(i < sBytes.Length)
{
bytes[j] = Byte.Parse(str.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}

Maybe it would work..

Good luck!
Oh, sorry, there's lots of mistakes in the code earlier code.

I tested this, and it worked, so be my guest! :)


string sBytes = "A509DE5B";
int i=0, j=0;
Byte[] bytes = new Byte[(int)(sBytes.Length/2)];
while(i < str.Length)
{
bytes[j] = Byte.Parse(sBytes.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}


byte[] bytes = new byte[str.Length / 2];
for(int i = 0; i < str.Length / 2; i++)
bytes [i] = Byte.Parse(str.Substring(i * 2, 2), NumberStyles.HexNumber);

works fine... THX

But I wonder why there's no such function like ToCharArray for string object which produces byte array. In many cases functions from .NET Framework uses byte arrays, not char arrays :(

Try this:

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

Good luck!

Newbie


I have tried this

System.Text.

ASCIIEncoding encoding =new System.Text.ASCIIEncoding();string queryStringKey =ConfigurationManager.AppSettings["queryStringKey"];byte[] key = encoding.GetBytes(queryStringKey);return key;

to achieve this

//byte[] Key = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6 };

but it is not working. What am I not getting? Newbie

String to convert into Double

Hello All,

I am having string object coming from a DataSet. It can contain either the Numeric Strings (like "123","123.23",...) or even the Character string (Like "America","Britain"...).

Now, I am assigning this value to another column in the dataset whose datatype is Doube. Now, I wanted to check before assigning whether whatever the String I am getting from the Source column can it be converted to Double or not?

i.e I want to know is there any object/method in .Net Framework using which I can know whether I can convert one datatype to another datatype or not?

Any help regarding this would be great.

Thanks in Advance,
Areef.Hi Areef,
I am not familiar with such an object, but you can use Double.TryParse to perform your task.
Hi pmd_areef,

Try the following for testing if value is a Double. Example:


[C#]
/// <summary>
/// Is the value supplied numeric (Integer, Double).
/// </summary>
/// <param name="number">Value to test</param>
/// <returns></returns>
public bool IsNumeric(object number)
{
double tempResult;
return IsNumeric(number, out tempResult);
}

public bool IsNumeric(object number, out double result)
{
return Double.TryParse(number.ToString(), System.Globalization.NumberStyles.Any,
System.Globalization.NumberFormatInfo.InvariantInfo, out result);
}


Hope this helps.

String to Control.ClientId

Hi.
Is there a way I can convert a string (let's say it's"vw501") sent by a querystring, to a Control's ClientID, like myMultiView.SetActiceView(vw501) ?

I've tried this, which fails:
Dim vName As String = TRim(Request.Querystring("vName"))
myMultiView.SetActiveView(vName)

Regards,

Roy

The FindControl method might help you there. Seehttp://msdn2.microsoft.com/de-de/library/system.web.ui.control.findcontrol.aspx

Make sure you use the FindControl method on the Control your views are nested in. Say if your Views are inside a Form named form1, like so:

myMultiView.SetActiveView( form1.FindControl(vName) )


Thanks a lot :-)
It works!

Roy

string to control name

I am looking for the way to convert a string, say it's called sTemp, to the actual control name.
I have say cMyControl as Control.
I want to set cMyControl = sTemp
I can't seem to find the right way to convert the string.

Thanks all,

ZathHi Zath,
You are trying to equal a string to a type Control. Which does not make sense. Its like equalling a line of text to your monitor. A Control has so many properties, like control ID, child controls, Parent and blah blah. So now, what you are trying to achieve and why
Thanks for the reply.

I have 4 imagas on a page. Depending on the number in the db field, I want the number of images to be visible.


'For i = 1 To intCnt 'intCnt is the number in the field
' sTmp = ("imgTest" & i) 'For the image names - imgTest1, imgTest2......
' j = CType(sTmp, Control) ' This line doesn't work
' j.Visible = True
'Next

Now it can be done with some if then statements, but if I ever increase the number above 4 in the db, then I will have to adjust the code.
And all the images are the same.
If there is a better way to do this, any suggestions are appreciated.

Zath

For i = 1 To intCnt
j = FindControl("imgTest" + i.ToString())

If Not j Is Nothing Then
j.Visible = True
End If
Next


Cool, thanks! Worked great.

Should have thought of that. I use the findcontrol for datagrid templates all the time....

Zath

String to date

I have a string which contains a date in "MM/dd/yyyy" format. How to I convert that in VB to "dd/MM/yyyy"

Please see this post.

http://forums.asp.net/1167602/ShowPost.aspx


Thanks for that

String to Date conversion

Im trying to convert the input of several dropdownlists into a Date, but I can get an error and dont know how to convert these fields to a date type...
This is the code:
Dim BirthDate As DateTime = CType(ddlDay.SelectedValue + ddlMonth.SelectedValue + ddlYear.SelectedValue, Date)
And now im here anyways :p ...how can I calculate someones age when I have his birth date?

It would probably be best if you keep the two types the same. Try using this:

Dim BirthDate As DateTime = CType(ddlDay.SelectedValue & "/" & ddlMonth.SelectedValue & "/" & ddlYear.SelectedValue, DateTime)


Try using something like this, for the calculation (assuming a sub, based on a button's click event):

Sub getDiff(Source as Object, E as EventArgs)
Dim myBirth as DateTime
Dim sDate as String
Dim Age As Integer
sDate=ddMonth.SelectedItem.Value & "/" & ddDay.SelectedItem.Text & "/" & ddYear.SelectedItem.Text
myBirth=cDate(sDate)
Age=DateTime.Now.Year - myBirth.Year
If DateTime.Now.Month < myBirth.Month Or (DateTime.Now.Month = myBirth.Month And DateTime.Now.Day < myBirth.Day) Then
Age = Age - 1
End If
lblDate.text="Age=" & Age.ToString
End Sub

Check out full code sample:
http://aspnet101.com/aspnet101/aspnet/codesample.aspx?code=calcage


Hi Peter Smith,

Give the following a try. Example:

Dim tempAsString = ddlDay.SelectedValue + "/" + ddlMonth.SelectedValue + "/" + ddlYear.SelectedValue
Dim birthDateAs DateTime = DateTime.Parse(temp)

The following function can be used to calculate Age, given a BirthDate. Example:

Public Shared Function Age(ByVal dateOfBirth As DateTime) As Integer
If DateTime.Today.Month < dateOfBirth.Month Or DateTime.Today.Month = dateOfBirth.Month And DateTime.Today.Day < dateOfBirth.Day Then
Return DateTime.Today.Year - dateOfBirth.Year - 1
Else
Return DateTime.Today.Year - dateOfBirth.Year
End If
End Function

Hope this helps.

String To Decimal

Hi,

How can I convert from string (Text Box) to Decimal (addition some entries then get result)

Thanks,

http://tinyurl.com/aqpgm

To Decimal method.

Please can u write thz method

sorry for disturbing


cavalry wrote:

Please can u write thz method

Scroll down just a little bit on that link above and therz the method in both VB and C#


Hi again,

i see the like but

Access to the requested URL is not allowed!

there is a ristriction to it in my city, so plz copy a paste here

sorry again


thank u its DONE

i've Declare

Dim Grade1 as Double=Grade1.Text

Dim Grade2 as Double=Grade2.Text

Dim Grade as double = Grade1+Grade2

Thanks Alot

String to DateTime?

If i have this in my Database in a column of VARCHAR

2006/12/28 18:35:10

can i convert it to date time in C# ? I attempted this?

int

result =DateTime.Compare((DateTime)ds2.Tables[0].Rows[0].ItemArray[1], (DateTime)ds2.Tables[0].Rows[1].ItemArray[1]);

which basically is taking two values in that format and comparing them but i get a invalid cast exception. And importing them into SQL As datetime is not possible.

do i have to convert it to an int first? or strip out the "/" and the ":" ? is it even possible?

thanks in advance,

mcm

UseDateTime.TryParse.

Yeah Man,

worked like a charm.

mcm


you can use

Convert.ToDateTime(string)


Convert.ToDateTime produced the same cast error as my other attempt. by TryParse worked.

yay

String to Enumeration

Hello,

How do I convert a string an enumeration value?

I have the following Enum:

Public Enum MyEnum
Book = 1
Movie
End Enum

Basically, I have a variable of type MyEnum and I want to define a
value to it:

Dim MyString As String = "Book"
Dim MyVar As MyEnum = MyString

I am getting an error.
I then tried:
Dim MyVar As MyEnum = CType(MyString, MyEnum)

This is still not working.
Any idea of how to solve this?

Thanks,
MiguelFor outputing the string, just use MyEnum.ToString(). And to reverse the
operation, use Enum.Parse.

String to Enum

Hello,

How do I convert a string an enumeration value?

I have the following Enum:

Public Enum MyEnum
Book = 1
Movie
End Enum

Basically, I have a variable of type MyEnum and I want to define a value to it:

Dim MyString As String = "Book"
Dim MyVar As MyEnum = MyString

I am getting an error.
I then tried:
Dim MyVar As MyEnum = CType(MyString, MyEnum)

This is still not working.
Any idea of how to solve this?

Thanks,
Miguel

Here's how it's done in C# (should be similar for VB)

enum EType {AAA, BBB, CCC};protected void Button1_Click(object sender, EventArgs e) { EType Test; Test = (EType)Enum.Parse(typeof(EType),"AAA"); }

Hello,

Here is a sample for you:

Imports SystemPublicClass ParseTest <FlagsAttribute()> _Enum Colors Red = 1 Green = 2 Blue = 4 Yellow = 8EndEnumPublicSharedSub Main() Console.WriteLine("The entries of the Colors Enum are:")Dim colorNameAsStringForEach colorNameIn [Enum].GetNames(GetType(Colors)) Console.WriteLine("{0}={1}", colorName, Convert.ToInt32([Enum].Parse(GetType(Colors), colorName)))Next colorName Console.WriteLine()Dim myOrangeAs Colors = CType([Enum].Parse(GetType(Colors),"Red, Yellow"), Colors) Console.WriteLine("The myOrange value {1} has the combined entries of {0}", myOrange, Convert.ToInt64(myOrange))EndSubEndClass'This code example produces the following results:''The entries of the Colors Enum are:'Red=1'Green=2'Blue=4'Yellow=8''The myOrange value 9 has the combined entries of Red, Yellow'
More details are here:http://msdn2.microsoft.com/en-us/library/essfb559.aspx

string to formated datetime

how can I convert a string like this "10/04" meaning octuber/2004 to a valid
DateTime?
"Alejandro Penate-Diaz" wrote:

> how can I convert a string like this "10/04" meaning octuber/2004 to a valid
> DateTime?
>
CDate function:

http://msdn.microsoft.com/library/d.../vsfctcdate.asp

Check the parameters that CDate is expecting. You may need to do some text
parsing and string manipulation before calling CDate.
You will use the .ParseExact method of DateTime.

Dim dt as DateTime
dt = DateTime.Parse( "10/04", "MM/yy" )

DateTime dtC = DateTime.Parse( "10/04", "MM/yy" );

HTH,

bill

"Alejandro Penate-Diaz" <alexware69@.hotmail.com> wrote in message
news:%23dwiz$jJFHA.2136@.TK2MSFTNGP14.phx.gbl...
> how can I convert a string like this "10/04" meaning octuber/2004 to a
valid
> DateTime?

string to formated datetime

how can I convert a string like this "10/04" meaning octuber/2004 to a valid
DateTime?
"Alejandro Penate-Diaz" wrote:

> how can I convert a string like this "10/04" meaning octuber/2004 to a val
id
> DateTime?
>
>
CDate function:
http://msdn.microsoft.com/library/d.../>
ctcdate.asp
Check the parameters that CDate is expecting. You may need to do some text
parsing and string manipulation before calling CDate.
You will use the .ParseExact method of DateTime.
Dim dt as DateTime
dt = DateTime.Parse( "10/04", "MM/yy" )
DateTime dtC = DateTime.Parse( "10/04", "MM/yy" );
HTH,
bill
"Alejandro Penate-Diaz" <alexware69@.hotmail.com> wrote in message
news:%23dwiz$jJFHA.2136@.TK2MSFTNGP14.phx.gbl...
> how can I convert a string like this "10/04" meaning octuber/2004 to a
valid
> DateTime?
>

String to Int error

Hello,

I need to convert a value from my textbox from string to int. It only hold the idea of an item and i need to send that as Stored Procedure value to fetch another value.
I now get the current error:

Input string was not in a correct format.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.FormatException: Input string was not in a correct format.

Source Error:

Line 97: Dim strComm As String = "spQMelderStatusGet"
Line 98: Dim str As String = Convert.ToString(lblStatus.Text)
Line 99: Dim ID As Int32 = Int32.Parse(str)
Line 100: Using loStat As SqlCommand = New SqlCommand(strComm)
Line 101:


Source File:D:\Source\Qualm\QMelder\StatusViewer.aspx.vb Line:99

And this is the code i'm using:

'Get status naamDim strCommAs String ="spQMelderStatusGet"Dim strAs String = Convert.ToString(lblStatus.Text)
Dim IDAs Int32 = Int32.Parse(str)
Using loStatAs SqlCommand =New SqlCommand(strComm)

Dim StatIDAs New SqlParameter()
StatID.ParameterName ="@dotnet.itags.org.StatusID" StatID.SqlDbType = SqlDbType.Int StatID.Direction = ParameterDirection.InputOutput StatID.Size = 2 StatID.Value = ID loStat.Parameters.Add(StatID) loStat.Connection = loConn loStat.CommandType = CommandType.StoredProcedure statReader = loStat.ExecuteReader lblStatus.Text = statReader("StatusNaam")
End Using

statReader.Close()


I've tried all kinds of ways, like converting the txtbox value to string and then to int but keep giving the same error, so most likely those codes weren't the right ones either.

If someone could help me out, tnx alot in advance.

Anoiks

Hi

before parsing String value in integer, check it's value ..

i hope . in ur case it's value is NULL or any Literal word


Hi

Hope I have understood your problem correctly.

Have you tried Convert.ToInt32("string").

But as I write, If the parse function you used fails to convert the string to integer, then may be the value entered in the text box either is non-convertible to integer data type or a conversion results in a out of range value. If you beleive it is a large integer value, can you try using a "float" or a "double" data type.

Worse case, can you convert your stored procedure type to accept an integer, I hope that is not hindering your requirement.

VJ


ok that was a stupid mistake, thanks alot i was too focussed on that part of code.
So i didnt notice i didnt fill the string in codes before that.Geeked

string to object

Hi

How to convert string to object?

i.e.

string objname = "Control1"

then some how use (function or method)

objname.visible = false

Hi There,

asmgx:

How to convert string to object?

i.e.

string objname = "Control1"

then some how use (function or method)

objname.visible = false

You can assign string value to object

e.g

string value = "control1";

object obj = value;

But not using string value to identify as object.

However, you can use string value as id and find the control.

e.g

Say you wanted to get textbox with id myTextBox

TextBox txt = (TextBox)this.FindControl("myTextBox"); //


in c#

String obj ="Control1";

Object objCast = ((Object)obj);

in vb

Dim objAsString = "Control1"

Dim objCastAsObject = (CType(obj,Object))

asmgx:

then some how use (function or method)

objname.visible = false

what exact you want to do?

String to Object?

Hi:

Can I convert a string to an object?

In my system I have the following:

Document.Title.Contains("Sony Camera")

The above returns an object of type Criterion, however, it will be saved in database,

when i read the above line as string, i want to make it an object of type Criterion, is this possible?

thank you.

Hi

(objectName) Document.Title.Contains("Sony Camera")

or

object.parse(Document.Title.Contains("Sony Camera"));


Hi

Thanks for the reply.

Don't I need any reflection? Just guessing.

Thanks,

Wednesday, March 28, 2012

String was not recognized as a valid DateTime Error

I am extracting a DateTime string from a SQL table, and I want to format it. However, when I try to convert the string to a datetime, I get the error:
"String was not recognized as a valid DateTime"
Here is my code:
private string dateFormatting(String theDate)
{
DateTime strDate;
strDate = Convert.ToDateTime(theDate);
strDate = strDate.ToString("M");
return strDate;
}
theDate has the value of "5/11/2005 5:10:25 PM". If I copy-and-paste the string into the code (instead of "theDate"), it compiles properly. However, leaving it in a variable always return the error above.
What might cause this problem?

Thanks

I'm having the same trouble... Can it be a bug?
Regards,
Luis Sim?es


Your variable "strDate" is a DateTime type. You are trying to fill a DateTime variable with a string:

strDate = strDate.ToString("M");
try this:

privatestring dateFormatting(string theDate)

{

DateTime strDate;

strDate = DateTime.Parse(theDate);

string stringDate = strDate.ToString("M");

return stringDate;

}



this may sound like a dumb question, but are you absoulutly sure that the date you paste in is the same date that your code is reciveing, as in have you place a breakpoint in and checked this for sure. One possibility is that the source of your date string has a different culture to the server running the convert.

On a side note, if your function only formats a date then why not only have yout functon accept a date rather then a string? In other words what context is this function performing its role of the conversion, is it from a databind or from a database object?


I'm not sure if it's gonna change anything but.. try to convert like this..
Convert.ToShortDateTime(variable);
anyway... I guess it changes nothing... except that the date will be returned different..
I am not sure if it's gonna change anything.. but.. try to use like this:

Convert.ToShortDateTime(var_name);
I don't know if it will make any difference at all.. I think it wont accutally... I mean.. about this error...

andrew_K wrote:

this may sound like a dumb question, but are you absoulutly sure that the date you paste in is the same date that your code is reciveing, as in have you place a breakpoint in and checked this for sure. One possibility is that the source of your date string has a different culture to the server running the convert.

On a side note, if your function only formats a date then why not only have yout functon accept a date rather then a string? In other words what context is this function performing its role of the conversion, is it from a databind or from a database object?

I am positive that the date I pasted is the same as the date that my code is receiving.

I have the function accept a string because it is called from a databind. I have tried converting the date before passing it to the function, and it returns the same error. I'd post the code, but I am at home now *-)


DevSlick wrote:

Your variable "strDate" is a DateTime type. You are trying to fill a DateTime variable with a string:

strDate = strDate.ToString("M");
try this:

privatestring dateFormatting(string theDate)

{

DateTime strDate;

strDate = DateTime.Parse(theDate);

string stringDate = strDate.ToString("M");

return stringDate;

}



It still returned the same error onstrDate = DateTime.Parse(theDate);
This is very weird.
Weird, it worked for me
This is driving me crazy. Here's the entire code. Maybe the problem is somewhere else. The stored procedure returns two values, the date and an id. Any help would be greatly appreciated!

protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource dsAdmin = new SqlDataSource();
dsAdmin.ConnectionString = "Data Source=(local);Initial Catalog=birdhair;Integrated Security=True";
dsAdmin.SelectCommand = "usp_Admin_ArchiveList";
dsAdmin.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
Parameter sParam1 = new Parameter();
sParam1.Name = "month";
sParam1.Type = TypeCode.Int32;
sParam1.DefaultValue = DateTime.Now.Month.ToString();
dsAdmin.SelectParameters.Add(sParam1);
Parameter sParam2 = new Parameter();
sParam2.Name = "Year";
sParam2.Type = TypeCode.Int32;
sParam2.DefaultValue = DateTime.Now.Year.ToString();
dsAdmin.SelectParameters.Add(sParam2);
DataGrid gridYear = new DataGrid();
gridYear.AutoGenerateColumns = false;
gridYear.DataSource = dsAdmin;
placeholder.Controls.Add(gridYear);
HyperLinkColumn column = new HyperLinkColumn();
column.DataNavigateUrlField = "LogID";
column.DataNavigateUrlFormatString = "edit.aspx?LogID={0}";
column.DataTextField = "LogTimeStamp";
column.DataTextFormatString = dateFormatting("{0}");
gridYear.Columns.Add(column);
gridYear.DataBind();
}
private string dateFormatting(String theDate)
{
DateTime strDate;
String stringDate;
strDate = DateTime.Parse(theDate);
stringDate = strDate.ToString("M");
return stringDate;
}

String was not recognized as a valid DateTime.

I am capturing a value from a text field and insert it into database of data type DateTime. I have used Convert.ToDateTime("stringdate") to convert it into datetime but i get the above error. But when I converted DateTime value to string and then converted it into DateTime using above method it works fine. I don't know what I need to do.

thanx for any helpIt's likely because the DateTime class can't figure out what date format the string is in. If you use DateTime.Parse that might work or if you always know what format your string is in use DateTime.ParseExact, because with that you can specify the date format.
Try:

FromDate = Convert.ToDateTime(Request.Form["FromDate"].ToString()).Date;

Where FromDate is the txtField - I had trouble with this - Seems like going around the houses a bit to me, but it works.

Pete

Monday, March 26, 2012

string.Split() does not work?

The following code:

string strProductIDAndProductCategory = Convert.ToString(e.CommandArgument); // productidandproductcategory sent in the command argument
string [] strArrayProductIDAndProductCategory = strProductIDAndProductCategory.Split("/");

...gives me the following compile error:
The best overloaded method match for 'string.Split(params char[])' has some invalid arguments

What are these 'invalid arguments'?

when i change it from Split("/") to Split() it works just fine... what gives?

thanks"/" is a string and not a char[]

Try this


char[]splitOn = {'/'};
string [] strArrayProductIDAndProductCategory = strProductIDAndProductCategory.Split(splitOn);

or this

string [] strArrayProductIDAndProductCategory = strProductIDAndProductCategory.Split('/');