Showing posts with label asp. Show all posts
Showing posts with label asp. Show all posts

Saturday, March 31, 2012

String String Function

All the String functions like 'Len', 'Left', 'Right', 'Mid' etc. that
are available in ASP are supported by ASP.NET as well except for the
string function 'String'.

The 'String' function takes this form:

String(number, character)

which returns a string consisting of *character* which is repeated
*number* times. For e.g.

String(3, "$")

would return

$$$

or

String(5, "A")

would return

AAAAA

But when I try to use this function in ASP.NET, the following error
gets generated

'String' is a class type and cannot be used as an expression.

It's pretty obvious what makes ASP.NET generate the above error but
how do I make use of this 'String' function in ASP.NET? Is there any
equivalent string function in ASP.NET?

Actually my main intention is to replace the first 10 characters of a
text with dots irrespective of the no. of characters in the text (or
the 'Len' of the text) which is why I needed to use the 'String'
function. Had ASP.NET supported the 'String' function, then the
following would have served my purpose:

strText = "The quick brown fox jumps over the lazy dog."
strText = String(10, ".") & Mid(strText, 11, Len(strText))

I can't use the 'Replace' function since the first 10 characters (or,
for that matter, the entire text) can be a combination any characters
(even non-alphanumeric).string str = new string(' ', 10);

<rn5a@dotnet.itags.org.rediffmail.comwrote in message
news:1170864460.723705.243170@dotnet.itags.org.k78g2000cwa.googlegr oups.com...

Quote:

Originally Posted by

All the String functions like 'Len', 'Left', 'Right', 'Mid' etc. that
are available in ASP are supported by ASP.NET as well except for the
string function 'String'.
>
The 'String' function takes this form:
>
String(number, character)
>
which returns a string consisting of *character* which is repeated
*number* times. For e.g.
>
String(3, "$")
>
would return
>
$$$
>
or
>
String(5, "A")
>
would return
>
AAAAA
>
But when I try to use this function in ASP.NET, the following error
gets generated
>
'String' is a class type and cannot be used as an expression.
>
It's pretty obvious what makes ASP.NET generate the above error but
how do I make use of this 'String' function in ASP.NET? Is there any
equivalent string function in ASP.NET?
>
Actually my main intention is to replace the first 10 characters of a
text with dots irrespective of the no. of characters in the text (or
the 'Len' of the text) which is why I needed to use the 'String'
function. Had ASP.NET supported the 'String' function, then the
following would have served my purpose:
>
strText = "The quick brown fox jumps over the lazy dog."
strText = String(10, ".") & Mid(strText, 11, Len(strText))
>
I can't use the 'Replace' function since the first 10 characters (or,
for that matter, the entire text) can be a combination any characters
(even non-alphanumeric).
>


On Feb 7, 9:17 pm, "Aidy" <a...@dotnet.itags.org.noemail.xxxa.comwrote:

Quote:

Originally Posted by

string str = new string(' ', 10);
>
<r...@dotnet.itags.org.rediffmail.comwrote in message
>
news:1170864460.723705.243170@dotnet.itags.org.k78g2000cwa.googlegr oups.com...
>
>
>

Quote:

Originally Posted by

All the String functions like 'Len', 'Left', 'Right', 'Mid' etc. that
are available in ASP are supported by ASP.NET as well except for the
string function 'String'.


>

Quote:

Originally Posted by

The 'String' function takes this form:


>

Quote:

Originally Posted by

String(number, character)


>

Quote:

Originally Posted by

which returns a string consisting of *character* which is repeated
*number* times. For e.g.


>

Quote:

Originally Posted by

String(3, "$")


>

Quote:

Originally Posted by

would return


>

Quote:

Originally Posted by

$$$


>

Quote:

Originally Posted by

or


>

Quote:

Originally Posted by

String(5, "A")


>

Quote:

Originally Posted by

would return


>

Quote:

Originally Posted by

AAAAA


>

Quote:

Originally Posted by

But when I try to use this function in ASP.NET, the following error
gets generated


>

Quote:

Originally Posted by

'String' is a class type and cannot be used as an expression.


>

Quote:

Originally Posted by

It's pretty obvious what makes ASP.NET generate the above error but
how do I make use of this 'String' function in ASP.NET? Is there any
equivalent string function in ASP.NET?


>

Quote:

Originally Posted by

Actually my main intention is to replace the first 10 characters of a
text with dots irrespective of the no. of characters in the text (or
the 'Len' of the text) which is why I needed to use the 'String'
function. Had ASP.NET supported the 'String' function, then the
following would have served my purpose:


>

Quote:

Originally Posted by

strText = "The quick brown fox jumps over the lazy dog."
strText = String(10, ".") & Mid(strText, 11, Len(strText))


>

Quote:

Originally Posted by

I can't use the 'Replace' function since the first 10 characters (or,
for that matter, the entire text) can be a combination any characters
(even non-alphanumeric).- Hide quoted text -


>
- Show quoted text -


Thanks a lot, Aidy :-)

String String Function

All the String functions like 'Len', 'Left', 'Right', 'Mid' etc. that
are available in ASP are supported by ASP.NET as well except for the
string function 'String'.
The 'String' function takes this form:
String(number, character)
which returns a string consisting of *character* which is repeated
*number* times. For e.g.
String(3, "$")
would return
$$$
or
String(5, "A")
would return
AAAAA
But when I try to use this function in ASP.NET, the following error
gets generated
'String' is a class type and cannot be used as an expression.
It's pretty obvious what makes ASP.NET generate the above error but
how do I make use of this 'String' function in ASP.NET? Is there any
equivalent string function in ASP.NET?
Actually my main intention is to replace the first 10 characters of a
text with dots irrespective of the no. of characters in the text (or
the 'Len' of the text) which is why I needed to use the 'String'
function. Had ASP.NET supported the 'String' function, then the
following would have served my purpose:
strText = "The quick brown fox jumps over the lazy dog."
strText = String(10, ".") & Mid(strText, 11, Len(strText))
I can't use the 'Replace' function since the first 10 characters (or,
for that matter, the entire text) can be a combination any characters
(even non-alphanumeric).string str = new string(' ', 10);
<rn5a@.rediffmail.com> wrote in message
news:1170864460.723705.243170@.k78g2000cwa.googlegroups.com...
> All the String functions like 'Len', 'Left', 'Right', 'Mid' etc. that
> are available in ASP are supported by ASP.NET as well except for the
> string function 'String'.
> The 'String' function takes this form:
> String(number, character)
> which returns a string consisting of *character* which is repeated
> *number* times. For e.g.
> String(3, "$")
> would return
> $$$
> or
> String(5, "A")
> would return
> AAAAA
> But when I try to use this function in ASP.NET, the following error
> gets generated
> 'String' is a class type and cannot be used as an expression.
> It's pretty obvious what makes ASP.NET generate the above error but
> how do I make use of this 'String' function in ASP.NET? Is there any
> equivalent string function in ASP.NET?
> Actually my main intention is to replace the first 10 characters of a
> text with dots irrespective of the no. of characters in the text (or
> the 'Len' of the text) which is why I needed to use the 'String'
> function. Had ASP.NET supported the 'String' function, then the
> following would have served my purpose:
> strText = "The quick brown fox jumps over the lazy dog."
> strText = String(10, ".") & Mid(strText, 11, Len(strText))
> I can't use the 'Replace' function since the first 10 characters (or,
> for that matter, the entire text) can be a combination any characters
> (even non-alphanumeric).
>
On Feb 7, 9:17 pm, "Aidy" <a...@.noemail.xxxa.com> wrote:
> string str = new string(' ', 10);
> <r...@.rediffmail.com> wrote in message
> news:1170864460.723705.243170@.k78g2000cwa.googlegroups.com...
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> - Show quoted text -
Thanks a lot, Aidy :-)

String Stripping

Hi,

I am trying to create a page that will check user input against a value in database. This page will have a text box for user to enter serial #.
Serial # length is variable but last 3 digit is always number.
For examples:
W04051234-PAY001 in this example code is 1234-PAY
W05051234-PAT002 in this example code is 1234-PAT

A12056040-G001 in this example code is 6040-G
B11056080-SU001 in this example code is 6080-s

Which is the best approach to extract CODE from user input?

Any help will be appriciated.

Thank

TekinUse the Regular Expression class, RegExp with a regular expression that looks for:
4 digits (or is it 3?) followed by
dash
followed by 1 or letters

That expression is:
\d{4}\-[A-Za-z]+
Actually,

I would like to Trancate first 5 digits and last 3 digits.

For examples:
W04051234-PAY001 in this example code is 1234-PAY
If you are attempting to strip a specific group of characters, the String class has numerous useful methods. I encourage you to read about the String class in the .net docs. I think the SubString() and Length() methods will be useful.

String to a Class name

Hi,

I've got some classes to access different types of databases and I have a string variable that define the type of db I want to access. What I want to do if is pssible use the value of this variable to access the class. I have the following code now.


switch (dbType)
{
case "MSSQL": return MSSQL.msSQLDataSet(sqlString);
case "ACCESS": return ACCESS.msSQLDataSet(sqlString);
case "ORACLE": return ORACLE.msSQLDataSet(sqlString);
case "MYSQL": return MYSQL.msSQLDataSet(sqlString);

default: return null;
}

I want to do something like


SomekindOfTransformation(dbType).msSQLDataSet(sqlString)

instead of using theswitch statement

Thanks,Hi Arty,

You can achieve it using Object.GetType and Type.InvokeMember. VisitObject.GetType andType.InvokeMember for complete details.

Here is a sample code:

using System;
using System.Reflection;

// This sample class has a field, constructor, method, and property.
class MyType
{
Int32 myField;
public MyType(ref Int32 x) {x *= 5;}
public override String ToString() {return myField.ToString();}
public Int32 MyProp
{
get {return myField;}
set
{
if (value < 1)
throw new ArgumentOutOfRangeException("value", value, "value must be > 0");
myField = value;
}
}
}

class MyApp
{
static void Main()
{
Type t = typeof(MyType);
// Create an instance of a type.
Object[] args = new Object[] {8};
Console.WriteLine("The value of x before the constructor is called is {0}.", args[0]);
Object obj = t.InvokeMember(null,
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
Console.WriteLine("Type: " + obj.GetType().ToString());
Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]);

// Read and write to a field.
t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetField, null, obj, new Object[] {5});
Int32 v = (Int32) t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetField, null, obj, null);
Console.WriteLine("myField: " + v);

// Call a method.
String s = (String) t.InvokeMember("ToString",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);
Console.WriteLine("ToString: " + s);

// Read and write a property. First, attempt to assign an
// invalid value; then assign a valid value; finally, get
// the value.
try
{
// Assign the value zero to MyProp. The Property Set
// throws an exception, because zero is an invalid value.
// InvokeMember catches the exception, and throws
// TargetInvocationException. To discover the real cause
// you must catch TargetInvocationException and examine
// the inner exception.
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {0});
}
catch (TargetInvocationException e)
{
// If the property assignment failed for some unexpected
// reason, rethrow the TargetInvocationException.
if (e.InnerException.GetType() !=
typeof(ArgumentOutOfRangeException))
throw;
Console.WriteLine("An invalid value was assigned to MyProp.");
}
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {2});
v = (Int32) t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null);
Console.WriteLine("MyProp: " + v);
}
}

Hope this helps,
Appan
Thank you Appana, that helped me a lot.

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

Hi, I have a vb.net/asp.net 1.1 web application that may be used in
other cultures where dates are formatted differently. I have three
controls (either DropDowns or TextBoxes) one for year, one for month,
and one for day.
I'd like to be able to convert this to a DateTime type of variable and
not have to rely on or find the localization settings.
My idea was to populate the DateTime.Year, DateTime.Month and
DateTime.Day from the controls, (like Date.Year = txtYear.Text) but
those properties are read-only.
I know I could make a string like "12-19-2005" and do a
strDate.ToDateTime but that will break as soon as the application is
used where dd-mm-yyyy is the norm.
So If I have three variables representing year, month, and day what's
the best way to convert to Date without relying on any kind of
localization setting? Thanks!
Mattit works in ASPNET 2.0,
it should work in ASP.NET1.x
Dim MyDate As New DateTime(2005, 12, 19)
Daniel TIZON
MCP - MCSD.NET - MCT
"MattB" <somedudeus@.yahoo.com> a crit dans le message de news:
40osodF1b4pklU1@.individual.net...
> Hi, I have a vb.net/asp.net 1.1 web application that may be used in other
> cultures where dates are formatted differently. I have three controls
> (either DropDowns or TextBoxes) one for year, one for month, and one for
> day.
> I'd like to be able to convert this to a DateTime type of variable and not
> have to rely on or find the localization settings.
> My idea was to populate the DateTime.Year, DateTime.Month and DateTime.Day
> from the controls, (like Date.Year = txtYear.Text) but those properties
> are read-only.
> I know I could make a string like "12-19-2005" and do a strDate.ToDateTime
> but that will break as soon as the application is used where dd-mm-yyyy is
> the norm.
> So If I have three variables representing year, month, and day what's the
> best way to convert to Date without relying on any kind of localization
> setting? Thanks!
> Matt
Daniel TIZON wrote:
> it works in ASPNET 2.0,
> it should work in ASP.NET1.x
> Dim MyDate As New DateTime(2005, 12, 19)
>
Perfect. Thanks!

String to date error

Hi guys Ive got a slight problem..

When i run my asp.net page through visual studio the application works fine, however when i puslish it and view it over myhttp://localhost page i get the following error "Conversion from string "28/8/2007" to type 'Date' is not valid." when selecting dates from a calendar control i created.

Im thinking this is some formatting issue having to do with EU/US Date format, however im not too sure about it and with a few research there are some help files stating to use globalization and once again im not sure how that works.

What im doing is assigning a date within an arraylist (which are of type dates) to a Date variable as below

Dim tempDate asDatetempDate = NewDate.Item(0) // arraylist of containing dates
Would appreciate some help regarding this issue

Thanks :)

It is a en-eu related problem. This article should help

http://msdn2.microsoft.com/en-us/library/2h3syy57.aspx
thanks that was interesting, also found out that the root to the problem was due to regional settings under the aspnet user account, my currently logged on account was set to UK however the user account aspnet was still on US therefore it kept showing dates in US format

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 equation

Got a quick question that I cannot get to work at work!

I have a field in SQL server that is set as a varchar but contains data like
>50 or <2 which is actually a target percentage. I have data in another
table stored as Decimal(14,2) that is the actual percentage. I need to
extract the two and create a conditional formatting result in a datalist.

Basically it would be something like this.

Assume actualpercentage = 30
targetpercentage = >50

If actual percentagetargetpercentage = True then forecolor= "Green"
Else
forecolor = "Red"

In actual terms it would be like
If 30>50 = True then forecolor = "Green"
Else
forecolor = "Red"

Don't worry about setting the color I can get that accomplished if I could
just build the boolean expression. And trust me I know the way it is written
here seems weird but it represents what I need to test. Basically the target
percentage is anything above 50% so I need to test and see if the actual was
greater than the target. However, like I show before the target could be
anything like <2%

Thanks for any help, a function or any mechanism for that matter would be
great.

Marty UHi Mary,

Obviously the first thing to do is to parse your varchar field. You stated
that your column "contains data like >50 or <2" - you need to get more
specific than that, becuase in essence, you have stored 2 different things
in the column, and the first thing you need is to split your string into 2
pieces. The only way to do that is to know what all of the possible values
for the first (comparison operator) is, so that you can identify where
tosplit the data. Of course, this would have been much easier if you had
used 2 columns to store the 2 values; that is good database design. But once
you've identified all the possible values of the first part, you can create
a loop that loops through all of them and uses the index of the last
character to determine where to split the value. Once split into 2 values,
you need to create a loop which selects from various kinds of comparison
operators that correspond to the ones in your list of possibles, and builds
a comparison statement from one of them.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"Marty Underwood" <martman100@.insightbb.com> wrote in message
news:bczYb.341294$xy6.1700666@.attbi_s02...
> Got a quick question that I cannot get to work at work!
> I have a field in SQL server that is set as a varchar but contains data
like
> >50 or <2 which is actually a target percentage. I have data in another
> table stored as Decimal(14,2) that is the actual percentage. I need to
> extract the two and create a conditional formatting result in a datalist.
> Basically it would be something like this.
> Assume actualpercentage = 30
> targetpercentage = >50
> If actual percentagetargetpercentage = True then forecolor= "Green"
> Else
> forecolor = "Red"
> In actual terms it would be like
> If 30>50 = True then forecolor = "Green"
> Else
> forecolor = "Red"
>
> Don't worry about setting the color I can get that accomplished if I could
> just build the boolean expression. And trust me I know the way it is
written
> here seems weird but it represents what I need to test. Basically the
target
> percentage is anything above 50% so I need to test and see if the actual
was
> greater than the target. However, like I show before the target could be
> anything like <2%
> Thanks for any help, a function or any mechanism for that matter would be
> great.
> Marty U
>
Hi Marty,

Look at the String.Substring() method. It's overloaded. One version takes
one parameter, which is the starting index of the substring. It reads to the
end of the string. The other takes a second parameter which is the number of
characters to get. So, assuming that your data, as you said, has only 2
single-character comparison operators, you can get the 2 values from it by
using the String.Substring method(). Example:

Dim s As String = "<123"
Dim operator As String = s.Substring(0, 1)
Dim value As Integer = Convert.ToInt32(s.Substring(1))

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.

"Marty U" <anonymous@.discussions.microsoft.com> wrote in message
news:8ABD3BD8-4FD3-456D-8DA0-722D75DCD452@.microsoft.com...
> Thanks for the reply Kevin,
> The only two comparison operators would be the greater than, less than
operators. I would have split these into two different columns but the
customer never said they would be used for actual comparisons but just a
display mechanism. Now I don't have time to redesign the related objects
that would use the split column.
> I had an idea of creating a function that receives 3 items.
> Function ShowResult(ActualValue as Decimal, theOperator as String,
TargetValue as Decimal)
> Dim theResult as Boolean
> theResult = ActualValuetheOperatorTargetValue
> Select Case theResult
> Case "True"
> do something
> Case "False"
> do something
> End Select
> End Function
> I would use a Left(TargetValue, 1) to pass theOperator argument. Can you
look at this theory and give me an idea how I can pass these 3 items into a
function and get the desired result of whether it's true or false.
> Thanks again, I don't have time to harp on this since I have a deadline of
Friday and this is just a perk they would like to have.
Sounds good I will look into this tomorrow at work. Oh and by the way I did
split the column into two seperate columns today due to another issue I had
that was not worth the trouble. It was easier to modify six pages of code
and modify the database then to program with the data being combined in the
DB.

Marty U

"Kevin Spencer" <kevin@.takempis.com> wrote in message
news:e2rCPxk9DHA.452@.TK2MSFTNGP11.phx.gbl...
> Hi Marty,
> Look at the String.Substring() method. It's overloaded. One version takes
> one parameter, which is the starting index of the substring. It reads to
the
> end of the string. The other takes a second parameter which is the number
of
> characters to get. So, assuming that your data, as you said, has only 2
> single-character comparison operators, you can get the 2 values from it by
> using the String.Substring method(). Example:
> Dim s As String = "<123"
> Dim operator As String = s.Substring(0, 1)
> Dim value As Integer = Convert.ToInt32(s.Substring(1))
> --
> HTH,
> Kevin Spencer
> .Net Developer
> Microsoft MVP
> Big things are made up
> of lots of little things.
> "Marty U" <anonymous@.discussions.microsoft.com> wrote in message
> news:8ABD3BD8-4FD3-456D-8DA0-722D75DCD452@.microsoft.com...
> > Thanks for the reply Kevin,
> > The only two comparison operators would be the greater than, less than
> operators. I would have split these into two different columns but the
> customer never said they would be used for actual comparisons but just a
> display mechanism. Now I don't have time to redesign the related objects
> that would use the split column.
> > I had an idea of creating a function that receives 3 items.
> > Function ShowResult(ActualValue as Decimal, theOperator as String,
> TargetValue as Decimal)
> > Dim theResult as Boolean
> > theResult = ActualValuetheOperatorTargetValue
> > Select Case theResult
> > Case "True"
> > do something
> > Case "False"
> > do something
> > End Select
> > End Function
> > I would use a Left(TargetValue, 1) to pass theOperator argument. Can you
> look at this theory and give me an idea how I can pass these 3 items into
a
> function and get the desired result of whether it's true or false.
> > Thanks again, I don't have time to harp on this since I have a deadline
of
> Friday and this is just a perk they would like to have.

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?
>