Search the web
Sign In
New User? Sign Up
codesnips · Code Snippets
? Already a member? Sign in to Yahoo!

Yahoo! Groups Tips

Did you know...
Message search is now enhanced, find messages faster. Take it for a spin.

Best of Y! Groups

   Check them out and nominate your group.
Having problems with message search? Fill out this form to ensure your group is one of the first to be migrated to the new message search system.

Messages

  Messages Help
Advanced
Messages 1 - 30 of 48   Newest  |  < Newer  |  Older >  |  Oldest
Messages: Show Message Summaries   (Group by Topic) Sort by Date v  
#30 From: "Nauman Leghari" <laghari78@...>
Date: Sun Mar 9, 2003 9:27 am
Subject: [C#] Using XmlTextWriter to create an Xml file
laghari78
Online Now Online Now
Send Email Send Email
 
Using XmlTextWriter to write an Xml file
 
 
using System;
using System.Xml;
using System.Text;
 
public class MainClass
{
 public static void Main(string [] arg)
 {
  // To create an Xml file with the following format
  // <?xml version="1.0" encoding="Windows-1252" standalone="yes"?>
  // <directory>
  //   <files dir="c:\" />
  // </directory>
 
  XmlTextWriter xmlText = new XmlTextWriter("filename.xml", Encoding.Default);
 
  xmlText.Formatting = Formatting.Indented;
 
  xmlText.WriteStartDocument(true);
 
  // If you want to attach an Xsl file with the Xml then uncomment the following 2 lines
  // It actually adds the xml-stylesheet attribute
  // string xslText="type='text/xsl' href='../index.xsl'";
        // xmlText.WriteProcessingInstruction("xml-stylesheet", xslText);
 
  xmlText.WriteStartElement("directory"); // <directory>
 
  xmlText.WriteStartElement("files"); // <files>
 
  xmlText.WriteAttributeString("dir", "c:\\");
  
  xmlText.WriteEndElement(); // </files>
 
  xmlText.WriteEndElement(); // </directory>
 
  xmlText.WriteEndDocument();
 
  xmlText.Close();
 }
}

#29 From: "Nauman Leghari" <laghari78@...>
Date: Sat Mar 1, 2003 4:01 pm
Subject: [C#] PageCapturer Utility
laghari78
Online Now Online Now
Send Email Send Email
 
Intro:
The PageCapturer utility is used to download Web pages programmatically and save them onto hard disk.
 
File: PageCapturer.zip attached with this email.
 
Purpose:
I made this to help me organize the pages visited everyday into a separate directory. And through this way I can save each page automatically with out having to Save each file manually.
 
Feature Missing:
This utility only downloads the Text of the Web page, the images or other media linked is not downloaded.
 
ScreenShot:
 
 
Working:
You can either enter the link into the Link field and then press "Get Page" button or simply copy the url. The program checkes every 2 seconds for any url on the clip board. Currenly, only http:// and ftp:// files are supported.
 
When the page is downloaded completely, the link for the page is automatically added to the "List of Pages fetched today". The list is also saved as an xml file "index.xml" into each directory which is also loaded at the startup. The "View Index" button displays the "index.xml" file after transforming it with the xsl file "index.xsl". Whereas, the "View Page" button displays the selected page in the list. You can also view the page by double clicking the page on the list.
The code is simple and does not block from throwing any exception, therefore you might see some exceptions.
 
How-To Run:
Either load the solution into VS.NET and execute; or run the PageCapturer.exe in the bin\debug\ directory.
 
/regards,
Nauman Leghari
 
For any questions on this, email on laghari78@... :).

#28 From: "Nauman Leghari" <laghari78@...>
Date: Fri Feb 28, 2003 5:22 pm
Subject: [C#] Retrieve WebPage programmatically and Save in File
laghari78
Online Now Online Now
Send Email Send Email
 

// imports

using System;

using System.Net;

using System.IO;

using System.Text;

// capture webpage by using HttpWebRequest class and Save into file. File is saved in a separate directory for each day. Please check out the method to create directory daywise.

// create an object of HttpWebRequest

string link = www.microsoft.com;

Uri pageUri = new Uri(link);

HttpWebRequest pageRequest = (HttpWebRequest)WebRequest.Create(pageUri);

try

{

WebResponse pageRes = pageRequest.GetResponse();

StreamReader sr = new StreamReader(pageRes.GetResponseStream());

String pageText = sr.ReadToEnd();

SaveToFile( pageText );

}

catch(WebException we)

{

}

 

-----------------------------------------------------------------------------------------------------------

// SaveToFile function

-----------------------------------------------------------------------------------------------------------   

private void SaveToFile( string pageText )

{

// check whether the directory is present

string currDir = Directory.GetCurrentDirectory();

// getting current date

DateTime dt = DateTime.Now;

string todayDir = currDir + @"\" + dt.ToString("ddMMyyyy");

string indexPath = todayDir + @"\index.xml";

// check whether its there

if (!Directory.Exists(todayDir))

{

// create directory

Directory.CreateDirectory(todayDir);

// Write pageText to file

string pathName = todayDir + @"\WebPage.html";

StreamWriter writeFile = File.CreateText(pathName);

writeFile.Write(pageText);

writeFile.Close();

}

catch(Exception e)

{

}

 

} // End of SaveToFile function

 
// WARNING: Compiled by Outlook

#27 From: "Nauman Leghari" <laghari78@...>
Date: Fri Feb 28, 2003 5:11 pm
Subject: [C#] Retrieving Text on Clipboard
laghari78
Online Now Online Now
Send Email Send Email
 

// import

import System.Windows.Forms;

// get clipboard data and if any then show in MessageBox

// Retrieves the data from the clipboard.

IDataObject iData = Clipboard.GetDataObject();

// Determines whether the data is in text format.

if(iData.GetDataPresent(DataFormats.Text))

{   

        // do anything

        MessageBox.Show((String)iData.GetData(DataFormats.Text));

}

// See the DataFormats class for other types


#26 From: "Nauman Leghari" <laghari78@...>
Date: Fri Feb 28, 2003 5:08 pm
Subject: [C#] Opening a file with a Specific Application
laghari78
Online Now Online Now
Send Email Send Email
 

// Open an xml file into Internet Explorer

Process p = System.Diagnostics.Process.Start( "iexplore.exe" , "index.xml" );


#25 From: "Nauman Leghari" <laghari78@...>
Date: Tue Feb 4, 2003 8:51 pm
Subject: [C#] String Formatting
laghari78
Online Now Online Now
Send Email Send Email
 
How to do String formatting
...........................



private void Submit_Click(object sender, EventArgs e) {

try
{

string valueToConvert = Value.Text;

switch (FormatType.SelectedItem.Value)
{

// Number formats
case "Currency":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "C5" );
//you can add a number to the end to specify precision
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"C5\"
)";
break;
case "Decimal":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "D5" );
//you can add a number to the end to specify precision
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"D5\"
)";
break;
case "Scientific":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "E" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"E\"
)";
break;
case "Fixed-point":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "F5" );
//you can add a number to the end to specify precision
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"F5\"
)";
break;
case "General":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "G" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"G\"
)";
break;
case "Number":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "N" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"N\"
)";
break;
case "Percent":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "P" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"P\"
)";
break;
case "Round-trip":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "R" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"R\"
)";
break;
case "Hexadecimal":
FormattedValue.Text = decimal.Parse(valueToConvert).ToString( "X" );
FormatExpression.Text = "decimal.Parse(valueToConvert).ToString( \"X\"
)";
break;

// Date Formats
case "Short Date Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "d" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"d\"
)";
break;
case "Long Date Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "D" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"D\"
)";
break;
case "Short Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "t" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"t\"
)";
break;
case "Long Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "T" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"T\"
)";
break;
case "Full Date/Time Pattern (short time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "f" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"f\"
)";
break;
case "Full Date/Time Pattern (long time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "F" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"F\"
)";
break;
case "General Date/Time Pattern (short time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "g" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"g\"
)";
break;
case "General Date/Time Pattern (long time)":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "G" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"G\"
)";
break;
case "Month Day Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "M" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"M\"
)";
break;
case "RFC1123 Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "R" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"R\"
)";
break;
case "Sortable Date/Time Pattern; conforms to ISO 8601":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "s" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"s\"
)";
break;
case "Universal Sortable Date/Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "u" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"u\"
)";
break;
case "Universal Full Sortable Date/Time Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "U" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"U\"
)";
break;
case "Year Month Pattern":
FormattedValue.Text = DateTime.Parse(valueToConvert).ToString( "Y" );
FormatExpression.Text = "DateTime.Parse(valueToConvert).ToString( \"Y\"
)";
break;
case "Custom Date Time":
FormattedValue.Text = DateTime.Now.ToString( "yyyy/mm/dd" );
FormatExpression.Text = "DateTime.Now.ToString( \"yyyy/mm/dd\" )";
break;

default:
FormattedValue.Text = Value.Text;
break;



}

}
catch (Exception Ex) {

FormattedValue.Text = ""+Ex.Message+"";
FormatExpression.Text = String.Empty;

}

}

#24 From: "Nauman Laghari" <laghari78@...>
Date: Tue Dec 3, 2002 5:54 pm
Subject: Using MSN Alerts
laghari78
Online Now Online Now
Send Email Send Email
 

What are MSN Alerts?

 

MSN Alerts Service is a part of Microsoft .NET My Services Initiative. It enables the service provider to reach its users through Instant Messages. Note that it will work on any type of devices, either mobile or desktops.

 

List some example applications?

 

1)      Event Management Application: Notifies the user instantly of the event it registers.

2)      Order Tracking Application: User is instantly notified if any change occurred in the order status.

Etc. etc.

 

So, where can you find the SDK? Licensing?

 

The MSN Alert SDK is downloaded for free from the following URL.

 

http://download.microsoft.com/download/.netalerts/install/5.01/nt5xp/en-us/installalertssdkserver.exe

 

It also contains necessary licensing agreement information as MSN Alerts service in the production setup is not free of cost.

 

Building our Hello World MSN Alert Application:

 

The following listing demonstrates a sample Console Application for MSN Alerts. For all the classes, properties and methods involved in the sample, consult the SDK documentation. Note that you need to Add Reference to the Microsoft Notification SDK Type Library (msnotify.dll). This COM Component is automatically registered when you install the Developer’s SDK.

 

<code>

 

using System;

using System.Reflection;

using System.Runtime.InteropServices;

 

// the following namespace is automatically added when you add a

// reference to the Microsoft Notifications SDK Type Library. Because the

// MSN Alerts subsystem is built using COM therefore we need the

// System.Runtime.InteropServices to access the COM objects through

// Managed Code

 

using MSNOTIFYLib;

 

namespace AlertSample

{

      class MainClass

      {

            static void SetNotificationValues(MsnNotificationClass Alert)

            {

 

                  // set notification values

                  Alert.ID = "1234";

                  Alert.MessageID = "0";

 

                  // this is also fixed with the demo

                  Alert.SiteID = "140001000";

 

                  // directory where the dev edition of the toolkit is installed

                  Alert.SiteURL = "http://localhost/MsAlertsSdkServer";

                 

                  // activates when the user clicks on the Alert window

                  Alert.ActionURL = "/action.asp";

 

                  // activates when the user clicks on the 'change' text on the Alert window

                  Alert.SubscribeURL = "/subscr.asp";

 

                  Alert.BodyLanguage = "1033";

 

                  // icon shown on the top left corner

                  Alert.BodyIcon = "/car.png";

 

                  // body of the alert message

                  Alert.Body = "<TEXT>Hello World</TEXT>";

 

 

            }

 

            static void Main(string[] args)

            {

                  //

                  // TODO: Add code to start application here

                  //

 

                  // creating the required objects

                  MsnNotificationClass Alert = new MsnNotificationClass();

                  NotificationTransportClass Transport = new NotificationTransportClass();

                  NotificationsUtilityClass Util = new NotificationsUtilityClass();

 

                  // setting the destination url

                  Transport.DestinationUrl = "http://localhost/MSAlertsSDKServer/MSAlertsSDKServer.dll";

 

                  // setting username and password

                  // these values are embedded with the sample toolkit

                  // therefore these are only for demo purposes

                  string userName = "Adventure Works";

                  string password = "password";

 

           

                  SetNotificationValues(Alert);

 

                  Console.WriteLine("Alerts Submission System Started");

           

// passport id, acquire using Passport Sign-in, dummy // in this case to pop-up messages locally.

 

                  Alert.ToPID = "0x01234567:0x89abcdef";

 

                  Console.WriteLine("XML:");

                  Console.WriteLine(Alert.GetSerialization());

 

                  Transport.SendNotification(1,userName,password,Alert,1);

 

                  Transport.DrainNotifications(0);

 

            }

      }

}

 

</code>

 

After running the sample application, we see the following pop-up appearing from the bottom-right corner of your desktop.

 

 

Conclusion:

 

MSN Alerts Service is an exciting way to develop client centric applications. Your imagination is the only limit here.


#23 From: "Nauman Laghari" <laghari78@...>
Date: Tue Dec 3, 2002 2:04 am
Subject: [LINK] ASP.NET Roadmap
laghari78
Online Now Online Now
Send Email Send Email
 
#22 From: "Asim" <asimletters@...>
Date: Tue Dec 3, 2002 1:27 am
Subject: 'other' numeric format specifiers
asimletters
Offline Offline
Send Email Send Email
 
Here is an example of advanced Numeric Format Specifier , according to exact position of numerals
 
' Change the number to Telephone number format
 
'///////////////
Dim Mynumber As Double = 1234567890

Dim MyString As String = Mynumber.ToString("(###) ### - ####")
 
'///////////////
and the output is (123) 456 – 7890
 
------------------------------------------------
Further Details of advanced Numeric Format Specifiers are following:
Format character Name Description
0 Zero placeholder If the value being formatted has a digit in the position where the '0' appears in the format string, then that digit is copied to the output string. The position of the leftmost '0' before the decimal point and the rightmost '0' after the decimal point determines the range of digits that are always present in the output string.
# Digit placeholder If the value being formatted has a digit in the position where the '#' appears in the format string, then that digit is copied to the output string. Otherwise, nothing is stored in that position in the output string. Note that this specifier never displays the '0' character if it is not a significant digit, even if '0' is the only digit in the string. It will display the '0' character if it is a significant digit in the number being displayed.
. Decimal point The first '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored. The actual character used as the decimal separator is determined by the NumberDecimalSeparator property of the NumberFormatInfo object that controls formatting.
, Thousand separator and number scaling The ',' character serves two purposes. First, if the format string contains a ',' character between two digit placeholders (0 or #) and to the left of the decimal point if one is present, then the output will have thousand separators inserted between each group of three digits to the left of the decimal separator. The actual character used as the decimal separator in the output string is determined by the NumberGroupSeparator property of the current NumberFormatInfo object that controls formatting.

Second, if the format string contains one or more ',' characters immediately to the left of the decimal point, then the number will be divided by the number of ',' characters multiplied by 1000 before it is formatted. For example, the format string '0,,' will represent 100 million as simply 100. Use of the ',' character to indicate scaling does not include thousand separators in the formatted number. Thus, to scale a number by 1 million and insert thousand separators you would use the format string '#,##0,,'.

% Percentage placeholder The presence of a '%' character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the '%' appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.
E0

E+0

E-0

e0

e+0

e-0

Scientific notation If any of the strings 'E', 'E+', 'E-', 'e', 'e+', or 'e-' are present in the format string and are followed immediately by at least one '0' character, then the number is formatted using scientific notation with an 'E' or 'e' inserted between the number and the exponent. The number of '0' characters following the scientific notation indicator determines the minimum number of digits to output for the exponent. The 'E+' and 'e+' formats indicate that a sign character (plus or minus) should always precede the exponent. The 'E', 'E-', 'e', or 'e-' formats indicate that a sign character should only precede negative exponents.
\ Escape character In C# and the Managed Extensions for C++, the backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with traditional formatting sequences like "\n" (new line).

In some languages, the escape character itself must be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. Use the string "\\" to display "\".

Note that this escape character is not supported in Visual Basic; however, ControlChars provides the same functionality.

'ABC'

"ABC"

Literal string Characters enclosed in single or double quotes are copied to the output string literally, and do not affect formatting.
; Section separator The ';' character is used to separate sections for positive, negative, and zero numbers in the format string.
Other All other characters All other characters are copied to the output string as literals in the position they appear.
 
----------------------------------------------------------------------------------------------------------------------------------------------------
EXAMPLES :
 
Format Data type Value Output
##### Double 123 123
00000 Double 123 00123
(###) ### - #### Double 1234567890 (123) 456 – 7890
#.## Double 1.2 1.2
0.00 Double 1.2 1.20
00.00 Double 1.2 01.20
#,# Double 1234567890 1,234,567,890
#,, Double 1234567890 1235
#,,, Double 1234567890 1
#,##0,, Double 1234567890 1,235
#0.##% Double 0.086 8.6%
0.###E+0 Double 86000 8.6E+4
0.###E+000 Double 86000 8.6E+004
0.###E-000 Double 86000 8.6E004
[##-##-##] Double 123456 [12-34-56]
##;(##) Double 1234 1234
##;(##) Double -1234 (1234)


#21 From: "Asim" <asimletters@...>
Date: Tue Dec 3, 2002 1:17 am
Subject: 'common' Numeric Format
asimletters
Offline Offline
Send Email Send Email
 
Example of the most Common Decimal Numeric Format.
 
'Insert Commas after each thousand , with specified number of decimal precision.
 
'////////////////

Dim var As Decimal = 12454545.340456

txt_messages.Text = var.ToString("N8")  ' Where8 is the number of digits we want to display after decimal.

'////////////////

the Output is

12,454,545.34045600

In Output its clearly seen that our format specifier has inserted 2 0s to make the number of digits 8 after decimal AND also has inserted commas after Each Thousand.

----------------------------------------------------------------------------------

Further Format Specifier Details are following :

Format specifer Name Description
C or c Currency The number is converted to a string that represents a currency amount. The conversion is controlled by the currency format information of the NumberFormatInfo object used to format the number. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision given by the NumberFormatInfo is used.
D or d Decimal This format is supported for integral types only. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
E or e Scientific (exponential) The number is converted to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. One digit always precedes the decimal point. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used. The case of the format specifier indicates whether to prefix the exponent with an 'E' or an 'e'. The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.
F or f Fixed-point The number is converted to a string of the form "-ddd.ddd…" where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the NumberFormatInfo is used.
G or g General The number is converted to the most compact decimal form, using fixed or scientific notation. The precision specifier determines the number of significant digits in the resulting string. If the precision specifier is omitted, the number of significant digits is determined by the type of number being converted:
  • Int16 or UInt16: 5 digits
  • Int32 or UInt32: 10 digits
  • Int64 or UInt64: 19 digits
  • Single: 7 digits
  • Double: 15 digits
  • Decimal: 29 digits

Trailing zeros after the decimal point are removed, and the resulting string contains a decimal point only if required.

The resulting string uses fixed-point format if the exponent of the number (as produced by the 'E' format) is less than the number of significant digits, and greater than or equal to –4. Otherwise, the resulting string uses scientific format, and the case of the format specifier controls whether the format is prefixed with an 'E' or an 'e'.

N or n Number The number is converted to a string of the form "-d,ddd,ddd.ddd…", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. Thousand separators are inserted between each group of three digits to the left of the decimal point. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the NumberFormatInfo is used.
P or p Percent The number is converted to a string that represents a percent as defined by the NumberFormatInfo.PercentNegativePattern property or the NumberFormatInfo.PercentPositivePattern property. If the number is negative, the string produced is defined by the PercentNegativePattern and starts with a minus sign. The converted number is multiplied by 100 in order to be presented as a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by NumberFormatInfo is used.
R or r Round-trip The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces of precision for a Single. If the value is successfully parsed back to the same numeric value, then it is formatted using the general format specifer. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. Although a precision specifier can be appended to the round-trip format specifier, it is ignored. Round trips are given precedence over precision when using this specifier. This format is supported by floating-point types only.
X or x Hexadecimal The number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for the hexadecimal digits greater than 9. For example, use 'X' to produce 'ABCDEF', and 'x' to produce 'abcdef'. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. This format is supported for integral types only.


#20 From: "Asim" <asimletters@...>
Date: Mon Dec 2, 2002 9:27 pm
Subject: Custom date time formats
asimletters
Offline Offline
Send Email Send Email
 
You Can easily Customize the display for your date time.
 
'/////////////////////////////////

Dim mydate As DateTime = DateTime.Now
Dim show_date As string

show_date= mydate.ToString("MMM dd,yyyy hh:mm:ss")

'/////////////////////////////////

Simply Pass the format as a parameter of overloaded method ToString.

Help For Format Specifier is following

 

Format specifiers Current culture Time zone Output
d, M en-US GMT 12, 4
d MMMM en-US GMT 12 April
12
dddd MMMM yy gg en-US GMT Thursday April 01 A.D.
h , m: s en-US GMT 6 , 13: 12
hh,mm:ss en-US GMT 06,13:12
HH-mm-ss-tt en-US GMT 06-13-12-AM
hh:mm, G\MT z      en-US GMT 05:13 GMT +0
hh:mm, G\MT z      en-US GMT +10:00 05:13 GMT +10
hh:mm, G\MT zzz en-US GMT 05:13 GMT +00:00
hh:mm, G\MT zzz en-US GMT –9:00 05:13 GMT -09:00

#19 From: "Asim" <asimletters@...>
Date: Mon Dec 2, 2002 8:38 pm
Subject: Create a File (Sequential)
asimletters
Offline Offline
Send Email Send Email
 
It is assumed that you have already placed these 2 controls on your winform:
1: TextBox (txt_data)
2: Button (btn_save)
 
Now create an on_click method for btn_save
 
'//////////////////////////////////////////////////////////////

Private Sub btn_save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_save.Click

'Create a text file, and save contents of the textbox (txt_data.text) into the file

Dim output As FileStream

Dim filechooser As New SaveFileDialog()

Dim result As DialogResult = filechooser.ShowDialog

Dim filename As String

filechooser.CheckFileExists = False

If result = DialogResult.Cancel Then

Exit Sub

End If

filename = filechooser.FileName

output = New FileStream(filename, FileMode.Create, FileAccess.Write)

Dim data As [Byte]() = Encoding.ASCII.GetBytes(txt_data.Text)

output.Write(data, 0, data.Length)

output.Flush()

output = Nothing

End Sub

'//////////////////////////////////////////////////////////////


#18 From: "Asim" <asimletters@...>
Date: Fri Nov 29, 2002 1:20 am
Subject: Catch KeyCode
asimletters@...
Send Email Send Email
 
In many cases you might have come acrooss the situation that IF Enter Key is pressed than do this.
For Example, You want to take some Input from a user in a textbox and want to take some action if user press enter (or whatever) KEY.
Following is an easy sample to do so :
 
It is assumed that you have created a form and placed an input textbox on it.
 
'/////////////////////////////////////////////////////////////////////////
 
Private Sub txt_input_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txt_input.KeyDown

If e.KeyCode = Keys.Enter Then

'Do the desired task here

End If

End Sub

'/////////////////////////////////////////////////////////////////////////


#17 From: Asim <asimletters@...>
Date: Sat Nov 23, 2002 1:14 am
Subject: MultiThreaded Socket Server -I
asimletters@...
Send Email Send Email
 

A Typical Socket Server -Steps:
1: Create a TcpListener Object
2: Call Start Method of TcpListener Object (Now the server actually starts looking for any client connection.
3: To Receive the requesting Client Connection, Call AcceptSocket Method of TcpListner Object,It actually returns a socket(TcpClient) object. This is where you can start the communication (send/receive bytes) with the client. The is a Blocking method, you cant do anything after executing this method but communication with the client. You cant receive any other client connection and no other processing.
4: Processing Phase , Use Read and Write methods of networkstream object to communicate with the client.
5: When the client and server have finished communicating, the server closes the connection,Close method of socket (TcpClient) object. Most Servers will then go back to step number 3 and call AcceptSocket method to recive any new socket client connection.

One Problem associated with this scheme is that the step 4 blocks other requests while processing a client's request, so that no other client can connect with the server while the code that defines  the processing phase is executing. The most common technique for addressing this problem is to use Multithreaded servers, which place the processing phase code in a seperate threadWhen a Server receives a connection request, the server spawns, or creates,  a Thread to process the connection, leaving its TcpListener free to receive other connections.

Example of a simple Multithreaded Server can be found in Part II of this Article.

Asim



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now

#16 From: "Nauman Laghari" <laghari78@...>
Date: Fri Nov 22, 2002 10:32 am
Subject: Calling API to bring any window to the Foreground
laghari78
Online Now Online Now
Send Email Send Email
 

Calling API to bring any window to the Foreground

public class TopWindow

{

[DllImport("user32.dll")]

public static extern IntPtr FindWindow(String winClass, String winName);

[DllImport("user32.dll")]

public static extern bool SetForegroundWindow(IntPtr winHandle);

public void Run()

{

IntPtr winHandle =

FindWindow(null,"windowName");

SetForegroundWindow(winHandle);

}

}


#15 From: "Asim" <asimletters@...>
Date: Wed Nov 20, 2002 10:28 pm
Subject: My First Web Service
asimletters@...
Send Email Send Email
 
The Article teaches how to create a web service and consuming it in an ASP.NET Page
 
===========================================================
 
' //// Code Starts here, save the code in an MeasurementConversions.asmx file
<%@ WebService Language="VB" Class="MeasurementConversions"%>
 
Imports System.Web.Services
 
Public Class MeasurementConversions
 
    <WebMethod()> _
    Public Function InchesToCentimeters(decInches As Decimal) As Decimal
        Return decInches * 2.54
    End Function
 
    <WebMethod()> _
    Public Function CentimetersToInches(decCentimeters As Decimal) As Decimal
        Return decCentimeters / 2.54
    End Function
 
    <WebMethod()> _
    Public Function MilesToKilometers(decMiles As Decimal) As Decimal
        Return decMiles * 1.61
    End Function
 
    <WebMethod()> _
    Public Function KilometersToMiles(decKilometers As Decimal) As Decimal
        Return decKilometers / 1.61
    End Function
 
End Class
'////Code ends here
The simple classs in above code has 4 public functions. Each funtions is taking a parameter in and returning the converted result.
 
To consume the service from ASP.NET pages you have to perform the following steps
 
1: Its is assumed that you have already created the webservice (.asmx) file and it
is located somewhere on the web (always accessable through http,either local or remote)
 
2. Now Create a proxy class for the webservice in question through the following command.
 
>wsdl /l:vb /o:d:\test_proxy.vb http://server/MeasurementConversions.asmx?wsdl /n:mynamespace
 

3: Now Compile the prxy file in .dll library and store it in the BIN folder
 
>vbc /out:d:\bin\test_proxy.dll /t:library /r:system.web.dll,sytem.dll,system.sml.dll,sytem.web.services.dll,system.data.dll
 d:\test_proxy.vb
 
4.Now create an aspx page and consume ther service
 
<%@ page language="vb" %>
<%@ import namespace="mynamespace" %>
 
<script language="vb" runat=server>
 
sub page_load()
 
dim ws as new mynamespace.MeasurementConversions
 
lbl.text=ws.MilesToKilometers(1)
 
end sub
 
</script>
 

<html>
 
 <body> 
 
 <asp:label id="lbl" runat="server" />
 
</body>
 
</htm>
=================================end===================
simple enough ;-) ??
 

 

#14 From: "Asim" <asimletters@...>
Date: Wed Nov 20, 2002 10:17 pm
Subject: Socket Client (VB.NET)
asimletters@...
Send Email Send Email
 

Following piece of code establishes a socks based connection to any server (localhost in this case) as port 13, If at port 13 there is some socks listner running to accept this connection, no error will appear and connection will be established correctly. else the code throws an exception saying no listener found at the specified address.Using this code u can connect to any socket server waiting for tcp socks connection. The code prints the welcome message from socket listner to the the console and sends the welcome message from itself as well.

Namespaces to be used:
system.net.sockets (classes: networkstream,tcpclient)
system.text  (classes: encoding class only)
 
Copy Paste the code in a .VB file , compile and excute !! before executing this code u better run socket listener first .
 
 
'//////////////// Listner Code starts here

Imports System.Net.Sockets

Imports System.Text

Module Module1

Sub Main()

Dim tcpClient As New TcpClient()

Try

tcpClient.Connect("127.0.0.1", 13)

Dim networkStream As NetworkStream = tcpClient.GetStream()

If networkStream.CanWrite And networkStream.CanRead Then

' Does a simple write.

Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there")

networkStream.Write(sendBytes, 0, sendBytes.Length)

' Reads the NetworkStream into a byte buffer.

Dim bytes(tcpClient.ReceiveBufferSize) As Byte

networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

' Returns the data received from the host to the console.

Dim returndata As String = Encoding.ASCII.GetString(bytes)

Console.WriteLine(("This is what the host returned to you: " + returndata))

Else

If Not networkStream.CanRead Then

Console.WriteLine("You can not write data to this stream")

tcpClient.Close()

Else

If Not networkStream.CanWrite Then

Console.WriteLine("You can not read data from this stream")

tcpClient.Close()

End If

End If

End If

Catch e As Exception

Console.WriteLine(e.ToString())

End Try

End Sub

End Module

'//////////////// Listner Code ends here


#13 From: "Asim" <asimletters@...>
Date: Wed Nov 20, 2002 10:09 pm
Subject: Socket Listner (VB.NET)
asimletters@...
Send Email Send Email
 
Running Following piece of code, opens a port number 13 on localhost, Starts listening the port,accepts any incoming connections (one only I think).
After establishing the connection we send a welcome message to the client application and receive the data from client, and display it on console.
 
Namespaces to be used:
system.net.sockets (classes: tcplistner,networkstream,tcpclient)
system.text  (classes: encoding class only)
 
Copy Paste the code in a .VB file , compile and excute !!
 
 
'//////////////// Listner Code starts here
 

Imports System.Net.Sockets

Imports System.Text

Module Module1

Sub Main()

Const portNumber As Integer = 13

Dim tcpListener As New TcpListener(portNumber)

tcpListener.Start()

Console.WriteLine("Waiting for a connection from client side socket application....")

Try

'Accept the pending client connection and return a TcpClient initialized for communication.

Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()

Console.WriteLine("Connection accepted.")

Dim networkStream As NetworkStream = tcpClient.GetStream()

Dim responseString As String = "Welcome, You have successfully connected to me."

Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)

'Following message goes to client application

networkStream.Write(sendBytes, 0, sendBytes.Length)

Console.WriteLine(("Message Sent /> : " + responseString))

'Any communication with the remote client using the TcpClient can go here.

'

'///// Reads from client and display

If networkStream.CanRead Then

' Reads the NetworkStream into a byte buffer.

Dim bytes(tcpClient.ReceiveBufferSize) As Byte

networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

' Returns the data received from the client to the Server console.

Dim returndata As String = Encoding.ASCII.GetString(bytes)

Console.WriteLine(("::This is what the client saying : " + returndata.Trim()))

End If

'///// Reads from client and display

'//////

'Close TcpListener and TcpClient.

tcpClient.Close()

tcpListener.Stop()

Catch e As Exception

Console.WriteLine(e.ToString())

Exit For

End Try

End Sub

End Module

 

'//////////////// Listner Code ends here


#12 From: "Nauman Laghari" <laghari78@...>
Date: Tue Nov 19, 2002 8:22 am
Subject: [ASP.NET] Changing Width of each column in a datagrid
laghari78
Online Now Online Now
Send Email Send Email
 
Implement the OnItemCreated event for the datagrid.

Then set
System.Web.UI.WebControls.DataGridItemEventArgs.Item.Cells[<columnno>].W
idth = <width>

                 private void dGrid_ItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
                 {
                         e.Item.Cells[0].Width = 270;
                 }

#11 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 8:35 am
Subject: [C#] Getting Caret Rate
laghari78
Online Now Online Now
Send Email Send Email
 
using System;
 
public class Caret
{
  [System.Runtime.InteropServices.DllImport("user32.dll")]
  public extern static bool SetCaretBlinkTime(uint uMSeconds);
 
  [System.Runtime.InteropServices.DllImport("user32.dll")]
  public extern static uint GetCaretBlinkTime();
 
 
 public static void Main()
 {
  double i = GetCaretBlinkTime();
  Console.WriteLine("{0}",i);
 }
 
}

#10 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 8:35 am
Subject: [C#] Executing Process (ShellExecute)
laghari78
Online Now Online Now
Send Email Send Email
 
using System;
using System.Diagnostics;
 
public class ShellExecuter
{
 public static void Main()
 {
  Process.Start("test.doc");
  
 }
}

#9 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:43 am
Subject: [LINK] ROTOR for Linux
laghari78
Online Now Online Now
Send Email Send Email
 
#8 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:42 am
Subject: [ASP.NET] Tracking Current Row in a Datagrid
laghari78
Online Now Online Now
Send Email Send Email
 
 
<asp:datagrid id="gridPub" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn HeaderText="Row Number">
<ItemTemplate>
<%# Container.ItemIndex+1 %>
</ItemTemplate>
</Columns>
</asp:datagrid>
%# Container.ItemIndex+1 %>%# DataBinder.Eval(Container.DataItem,"Address") + " " + DataBinder.Eval(Container.DataItem,"City") + "" %>

#7 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:42 am
Subject: [ASP.NET] Hyperlink Column in a Datagrid
laghari78
Online Now Online Now
Send Email Send Email
 
 
     <asp:HyperLinkColumn HeaderText="more..."
          DataTextField="pubId"
       DataTextFormatString="More about {0}"
       DataNavigateUrlField="pubId"
       DataNavigateUrlFormatString="more.aspx?pubId={0}" />
 

#6 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:41 am
Subject: [ASP.NET] Manipulating Several Fields from a DB in a single column
laghari78
Online Now Online Now
Send Email Send Email
 
 
%# DataBinder.Eval(Container.DataItem,"Name") %>%# DataBinder.Eval(Container.DataItem,"Address") + " " + DataBinder.Eval(Container.DataItem,"City") + "" %>%# Container.ItemIndex+1 %>%# DataBinder.Eval(Container.DataItem,"Name") %>%# DataBinder.Eval(Container.DataItem,"Address") + " " + DataBinder.Eval(Container.DataItem,"City") + "" %>%# Container.ItemIndex+1 %>%# DataBinder.Eval(Container.DataItem,"Name") %>%# DataBinder.Eval(Container.DataItem,"Address") + " " + DataBinder.Eval(Container.DataItem,"City") + "" %>%# Container.ItemIndex+1 %>%# DataBinder.Eval(Container.DataItem,"Name") %>%# DataBinder.Eval(Container.DataItem,"Address") + " " + DataBinder.Eval(Container.DataItem,"City") + "" %><asp:datagrid id="gridPub" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn HeaderText="Publisher">
<ItemTemplate>
<asp:Label Runat="server"><%# DataBinder.Eval(Container.DataItem,"Address") + " <b>" + DataBinder.Eval(Container.DataItem,"City") + "</b>" %></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>

#5 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:40 am
Subject: [ASP.NET] Using ItemCommand to Get all values from the DataGrid Row
laghari78
Online Now Online Now
Send Email Send Email
 
Database: Biblio.mdb -- Table: Publishers

aspx Page:

<%@ Page language="c#" Codebehind="PItemCommand.aspx.cs" AutoEventWireup="false" Inherits="Problems.PItemCommand" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>PItemCommand</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="
http://schemas.microsoft.com/intellisense/ie5">
 </HEAD>
 <body>
  <form id="PItemCommand" method="post" runat="server">
   <P>
    <asp:DataGrid id="dGrid" runat="server" AutoGenerateColumns="False">
     <Columns>
      <asp:BoundColumn DataField="PubId" HeaderText="PubId"></asp:BoundColumn>
      <asp:BoundColumn DataField="Name" HeaderText="Publisher"></asp:BoundColumn>
      <asp:BoundColumn DataField="Address" HeaderText="Address"></asp:BoundColumn>
      <asp:TemplateColumn HeaderText="City">
       <ItemTemplate>
        <asp:Label ID="lblCity" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"City")%>'></asp:Label>
       </ItemTemplate>
      </asp:TemplateColumn>
      <asp:TemplateColumn>
       <ItemTemplate>
        <asp:TextBox runat=server ID="txtNumber" Width="50"></asp:TextBox>
       </ItemTemplate>
      </asp:TemplateColumn>
      <asp:ButtonColumn Text="Select" HeaderText="Select"></asp:ButtonColumn>
     </Columns>
    </asp:DataGrid></P>
   <P>
    <asp:Label id="lblStatus" runat="server">Status</asp:Label></P>
  </form>
 </body>
</HTML>

CodeBehind Page:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Configuration;

namespace Problems
{
 /// <summary>
 /// Summary description for PItemCommand.
 /// </summary>
 public class PItemCommand : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid dGrid;
  protected System.Web.UI.WebControls.Label lblStatus;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here

   // Put user code to initialize the page here
   OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

   string strSql = "select PubId,Name,Address,City from Publishers";

   OleDbCommand myCommand = new OleDbCommand(strSql,myConnection);
    
   myConnection.Open();
   
   OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

   dGrid.DataSource = myReader;

   if (!(Page.IsPostBack))
   {
    dGrid.DataBind();
   }
  }

  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {   
   this.dGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dGrid_ItemCommand);
   this.Load += new System.EventHandler(this.Page_Load);

  }

  private void dGrid_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   string str = ">> ";
   str += e.Item.Cells[0].Text;
   str += "<br>" + e.Item.Cells[1].Text;
   str += "<br>" + e.Item.Cells[2].Text;
   str += "<br>" + ((Label)e.Item.Cells[0].FindControl("lblCity")).Text;
   str += "<br>" + ((TextBox)e.Item.Cells[4].FindControl("txtNumber")).Text;
    
   //e.Item.Cells[4].Text;

   lblStatus.Text = str;

   dGrid.DataBind();
  }
 }
}


#4 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:40 am
Subject: [ASP.NET] Selecting all columns in a row using the SelectedItemChange event
laghari78
Online Now Online Now
Send Email Send Email
 
In the aspx file 
 
<asp:datagrid id="gridPub" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="PubGrid_SelectedItemChange">
     <SelectedItemStyle BackColor="#99FF33"></SelectedItemStyle>
     <Columns>
      <asp:TemplateColumn HeaderText="Name">
       <ItemTemplate>
        <%# DataBinder.Eval(Container.DataItem,"Name") %>
       </ItemTemplate>
      </asp:TemplateColumn>
      <asp:BoundColumn DataField="Address"></asp:BoundColumn>
      <asp:TemplateColumn>
       <ItemTemplate>
        <asp:Label id="lblCity" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"City") %>' />
       </ItemTemplate>
      </asp:TemplateColumn>
      <asp:TemplateColumn>
       <ItemTemplate>
        <asp:TextBox id="txtName" Runat="server" Width=50 Text='<%# DataBinder.Eval(Container.DataItem,"City") %>' />
       </ItemTemplate>
      </asp:TemplateColumn>
      <asp:ButtonColumn runat="server" Text="select" HeaderText="Select" CommandName="select"></asp:ButtonColumn>
     </Columns>
    </asp:datagrid>
 
In the Codebehind file, for selected respective values from the above aspx file.
 
protected void PubGrid_SelectedItemChange(object source,
   System.EventArgs e)
  {
   label1.Text = "You selected " + ((DataBoundLiteralControl)gridPub.SelectedItem.Cells[0].Controls[0]).Text;
 
   label2.Text = "<br>And " + gridPub.SelectedItem.Cells[1].Text;
 
   label3.Text = "<br>And " + ((Label)gridPub.SelectedItem.Cells[2].FindControl("lblCity")).Text;
 
   label4.Text = "<br>And " + ((TextBox)gridPub.SelectedItem.Cells[3].FindControl("txtName")).Text;
  }
 

#3 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:39 am
Subject: [ASP.NET] Changing Row/Column Color Programatically
laghari78
Online Now Online Now
Send Email Send Email
 
See the ItemBound event of datagrid.
Database: biblio.mdb
Table: Publishers
 
aspx file:
-----------------------------------------
<%@ Page language="c#" Codebehind="PRowColor.aspx.cs" AutoEventWireup="false" Inherits="Problems.PRowColor" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>PRowColor</title>
  <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 </HEAD>
 <body>
  <form id="PRowColor" method="post" runat="server">
   <P><asp:datagrid id="dGrid" runat="server" AutoGenerateColumns="False">
     <Columns>
      <asp:BoundColumn DataField="PubId" HeaderText="PubId"></asp:BoundColumn>
      <asp:BoundColumn DataField="Name" HeaderText="Publisher"></asp:BoundColumn>
      <asp:BoundColumn DataField="Address" HeaderText="Address"></asp:BoundColumn>
      <asp:TemplateColumn HeaderText="City">
       <ItemTemplate>
        <%# DataBinder.Eval(Container.DataItem,"City") %>
       </ItemTemplate>
      </asp:TemplateColumn>
     </Columns>
    </asp:datagrid></P>
   <P><asp:label id="lblStatus" runat="server">Label</asp:label></P>
  </form>
 </body>
</HTML>
-------------------------------------------------
 
Codebehind file:
 
-------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Configuration;
 
namespace Problems
{
 /// <summary>
 /// Summary description for PRowColor.
 /// </summary>
 public class PRowColor : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid dGrid;
  protected System.Web.UI.WebControls.Label lblStatus;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here
   // Put user code to initialize the page here
   OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
 
   string strSql = "select PubId,Name,Address,City from Publishers";
 
   OleDbCommand myCommand = new OleDbCommand(strSql,myConnection);
    
   myConnection.Open();
   
   OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
 
   dGrid.DataSource = myReader;
 
   if (!(Page.IsPostBack))
   {
    dGrid.DataBind();
   }
  }
 
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {   
   this.dGrid.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dGrid_ItemDataBound);
   this.Load += new System.EventHandler(this.Page_Load);
 
  }
 
  private void dGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   // only apply on item and alternating item
   if (e.Item.ItemType == ListItemType.Item ||
    e.Item.ItemType == ListItemType.AlternatingItem)
   {
    // getting the index value ( or any other data cell value )
    string sVal = e.Item.Cells[0].Text;
    
    // changing the color or all even rows
    if ((Convert.ToInt32(sVal)%2) == 0)
    {
     // changing color for individial row
     e.Item.BackColor = System.Drawing.Color.Red;
 
     // changing color for individual column
     e.Item.Cells[0].BackColor = System.Drawing.Color.Green;
    }
   }
  }
 }
}
 

#2 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:39 am
Subject: [ASP.NET] Dynamically Changing the Color of Edited Items in a DataGrid
laghari78
Online Now Online Now
Send Email Send Email
 
#1 From: "Nauman Laghari" <laghari78@...>
Date: Mon Nov 18, 2002 6:38 am
Subject: [ASP.NET] Programmatically changing the color of a whole column in a datagrid
laghari78
Online Now Online Now
Send Email Send Email
 
 
         // previous email is changing the color of each cell
// this one is about chaning the complete column color change
 
see the ItemCreated event
same database file and table
 
aspx
-------
 
<%@ Page language="c#" Codebehind="PRowColor.aspx.cs" AutoEventWireup="false" Inherits="Problems.PRowColor" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>PRowColor</title>
  <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 </HEAD>
 <body>
  <form id="PRowColor" method="post" runat="server">
   <P><asp:datagrid id="dGrid" runat="server" AutoGenerateColumns="False">
     <Columns>
      <asp:BoundColumn DataField="PubId" HeaderText="PubId"></asp:BoundColumn>
      <asp:BoundColumn DataField="Name" HeaderText="Publisher"></asp:BoundColumn>
      <asp:BoundColumn DataField="Address" HeaderText="Address"></asp:BoundColumn>
      <asp:TemplateColumn HeaderText="City">
       <ItemTemplate>
        <%# DataBinder.Eval(Container.DataItem,"City") %>
       </ItemTemplate>
      </asp:TemplateColumn>
     </Columns>
    </asp:datagrid></P>
   <P><asp:label id="lblStatus" runat="server">Label</asp:label></P>
  </form>
 </body>
</HTML>
=========
 
Codebehind
-----------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Configuration;
 
namespace Problems
{
 /// <summary>
 /// Summary description for PRowColor.
 /// </summary>
 public class PRowColor : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid dGrid;
  protected System.Web.UI.WebControls.Label lblStatus;
  int itemCount = 0;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here
   // Put user code to initialize the page here
   OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
 
   string strSql = "select PubId,Name,Address,City from Publishers";
 
   OleDbCommand myCommand = new OleDbCommand(strSql,myConnection);
    
   myConnection.Open();
   
   OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
 
   dGrid.DataSource = myReader;
 
   if (!(Page.IsPostBack))
   {
    dGrid.DataBind();
   }
  }
 
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {   
   this.dGrid.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dGrid_ItemCreated);
   this.Load += new System.EventHandler(this.Page_Load);
 
  }
 
  private void dGrid_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   // test: calculating how many times the ItemCreated event is called
   itemCount ++;
   lblStatus.Text += " " + itemCount.ToString();
 
   // only apply on item and alternating item
   if (e.Item.ItemType == ListItemType.Item ||
    e.Item.ItemType == ListItemType.AlternatingItem)
   {
    string sVal = e.Item.Cells[0].Text;
    lblStatus.Text += " " + sVal;
 
    // changing color of whole column
    e.Item.Cells[2].BackColor = System.Drawing.Color.Red;
   }  
  }
 }
}

Messages 1 - 30 of 48   Newest  |  < Newer  |  Older >  |  Oldest
Advanced
Add to My Yahoo!      XML What's This?

Copyright © 2009 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Guidelines - Help