WinForms FAQ - Strings

Find answers for the most frequently asked questions
Expand All Collapse All

In this case, the dataobject is a memory stream. Here are code snippets that allow you to get/set CSV values from/to the clipboard in a manner compatible with Excel.

[C#]
private void GetCSVFromClipBoard_Click(object sender, System.EventArgs e)
{
	IDataObject o = Clipboard.GetDataObject();
	if(o.GetDataPresent(DataFormats.CommaSeparatedValue)) 
	{
		StreamReader sr = new StreamReader((Stream) o.GetData(DataFormats.CommaSeparatedValue));
		string s = sr.ReadToEnd();
		sr.Close();
		Console.WriteLine(s);
	}
}

private void CopyCSVToClipBoard_Click(object sender, System.EventArgs e)
{
	String csv = '1,2,3' + Environment.NewLine + '6,8,3';
	byte[] blob = System.Text.Encoding.UTF8.GetBytes(csv);
	MemoryStream s = new MemoryStream(blob);
	DataObject data = new DataObject();
	data.SetData(DataFormats.CommaSeparatedValue, s);
	Clipboard.SetDataObject(data, true);
}

[VB.NET]
Private Sub GetCSVFromClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
	Dim o As IDataObject = Clipboard.GetDataObject()
	If Not o Is Nothing Then
		If (o.GetDataPresent(DataFormats.CommaSeparatedValue)) Then
			Dim sr As New StreamReader(CType(o.GetData(DataFormats.CommaSeparatedValue), Stream))
			Dim s As String = sr.ReadToEnd()
			sr.Close()
			Console.WriteLine(s)
		End If
	End If
End Sub ’GetCSVFromClipBoard_Click

Private Sub CopyCSVToClipBoard_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
	Dim csv As String = '1,2,3' + Environment.NewLine + '6,8,3'
	Dim blob As Byte() = System.Text.Encoding.UTF8.GetBytes(csv)
	Dim s As New MemoryStream(blob)
	Dim data As New DataObject()
	data.SetData(DataFormats.CommaSeparatedValue, s)
	Clipboard.SetDataObject(data, True)
End Sub ’CopyCSVToClipBoard_Click
Permalink

.NET has excellent support for Regular Expressions. Get the excellent ‘Regular Expressions with .NET ‘, e-book by Dan Appleman. It has all that you need to get started.

Regular expressions really make string processing easier.

There are expressions that you can find on the web for everything from validating dates to phone numbers.

Permalink

Use the StringBuilder class to concatenate strings. This class reuses memory. If you add string members to concatenate them, there is extra overhead as new memory is allocated for the new string. If you do a series of concatenations using the strings (instead of StringBuilder objects) in a loop, you continually get new strings allocated. StringBuilder objects allocate a buffer, and reuse this buffer in its work, only allocating new space when the initial buffer is consumed. Here is a typical use case.

	StreamReader sr = File.OpenText(dlg.FileName); 
                string s = sr.ReadLine(); 
                StringBuilder sb = new StringBuilder(); 
                while (s != null) 
                { 
                     sb.Append(s); 
                     s = sr.ReadLine(); 
                } 
                sr.Close(); 
                textBox1.Text = sb.ToString(); 
Permalink

To convert an enum to string, do this:


string enumEntryAsString = Enum.GetName(typeof(TabSizeMode), TabSizeMode.FillToRight);

To convert a string to an enum type:


// Enclose this code within try/catch.
TabSizeMode sizeMode = Enum.Parse(typeof(TabSizeMode), '1');
(or)
TabSizeMode sizeMode = Enum.Parse(typeof(TabSizeMode), 'FillToRight');
Permalink

You can use the static DateTime.Parse or DateTime.ParseExact and catch any exceptions.

	System.DateTime myDateTime;
	bool isValid = true;
	try 
	{
    		myDateTime = System.DateTime.Parse(strMyDateTime);
	} 
	catch (Exception e) 
	{
    		isValid = false;
	}
Permalink

VB.NET has a IsNumeric method that you can use to recognize a Short, Integer, Long, Decimal or Single numeric type. From C#, you can use try/catch to look for a particular numeric type.

	//long for a Single
	Single num;
	try 
	{
    		num = Single.Parse(someString);
	} 
	catch (Exception e) 
	{
    		// if this is hit, someString is not a Single
	}
Permalink

You can use the TypeDescriptor class to handle this.

	Color redColor = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString('Red');
	string redString = TypeDescriptor.GetConverter(typeof(Color)).ConvertToString(Color.Red);

You can also use code such as

	System.Drawing.ColorConverter ccv = new System.Drawing.ColorConverter();
	this.BackColor = (Color) ccv.ConvertFromString('Red');
Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.