Tuesday, September 13, 2011

Both DataSource and DataSourceID are defined on ‘GridView1′. Remove one definition. – Bind multiple datasources to a gridview control


Both DataSource and DataSourceID are defined on ‘GridView1′.  Remove one definition.
OK, so this is the message that you get most of the times when you try to bind your gridview or any other bindable controls, to multiple DataSources.
 It happens most of the times when you bind your GridView control to an ObjectDataSouce or SqlDataSource on the design surface and then you try to bind the same GridView in code behind using the manual coding and sometimes it becomes necessary to do so in the scenarios of searching and manual paging etc.
(Binding to ObjectDataSource)




(Binding to manual DataSource)



GridView1.DataSource = null;
GridView1.DataSource = myDataTable;
GridView1.DataBind();
This is not going to solve the problem, the simples workaround is to set theDataSourceID to null.
GridView1.DataSourceID = null;   // String.Empty
GridView1.DataSource = dt;
GridView1.DataBind();
now this is going to work perfectly fine but DataGrid required a page developer to write custom code to handle simple operations such as paging, sorting, editing or deleting data, the GridView control can automatically handle these operations provided its bound data source control supports these capabilities and we know that this kind of custom binding will kill any chances to automate your GridView to handle all these operations automatically.
Simplest way to resolve this issue is to display your required data to the client and then bind back the GridView to your original datasouce by setting the DataSourceID to null again. That will bring back all your automation functionality back to the GridView.

Label vs. Literal in Asp.net


ใน ASP.NETจะมีเว็บคอนโทรลอยู่สองตัวที่ทำหน้าที่คล้ายๆกันคือแสดงผลส่วนที่เป็นข้อความปกติ Label และ Literal คำถามที่เกิดขึ้นคือ เมื่อไหร่ควรจะใช้ Labelและเมื่อไหร่ควรจะใช้ Literal
ข้อแตกต่างที่เห็นได้ชัดระหว่าง Label และ Literal จะแสดงให้เห็นด้วยตัวอย่างง่ายๆคือ
<asp:Label ID="TestLabel" runat="server">Label</asp:Label> <asp:Literal ID="TestLiteral" runat="server">Literal</asp:Literal> 
ซึ่งจะให้ผลลัพธ์เป็น
<span id="TestLabel">Label</span>
Literal
ซึ่งจะเห็นว่าผลลัพธ์ที่ได้นั้นแตกต่างกันตรงที่ Label มี span ครอบแต่ Literal ไม่มี และเมื่อดูจากต้นไม้การสืบทอด จะเห็นว่า Literalนั้นสืบทอดมาจากคลาส System.Web.UI.Control แต่ Label นั้นสืบทอดมาจากคลาสSystem.Web.UI.WebControlทำให้สามารถควบคุมรูปแบบการแสดงผลพวกสไตล์ต่างๆได้ นอกจากนี้ Label ยังมีประโยชน์อีกอย่างที่ไม่ค่อยมีคนรู้กันก็คือ ใช้สำหรับสร้าง tag Label นั่นเอง
<asp:Label id="label" AssociatedControlId="textbox"  Text="Username" runat="server" />  <asp:TextBox id="textbox" runat="server" /> 
จะได้ผลลัพธ์เป็น
<label for="textbox">Username</label> <input type="textbox" name="textbox" value="" /> 
ในทางกลับกัน Literal ก็มีข้อดีที่ช่วยให้โค้ด HTMLที่ได้นั้นสะอาดและเรียบร้อยกว่าการใช้ Label ซึ่งจากตัวอย่างแรกจะเห็นว่าLabel ให้ผลลัพธ์ที่มีจำนวนตัวอักษรมากกว่า Literal ถึง 28 ตัวอักษร
จากความแตกต่างข้างต้นก็จะได้หลักการใช้งานคร่าวๆคือ
ใช้ Literal เมื่อ
  • แสดงผลข้อความทั่วๆไป ซึ่งดีกว่าการฝังข้อความลงไปตรงๆเพราะสามารถนำไปใช้ทำ Localization ได้ทันที
  • สร้างสคริปต์
  • ใช้ในจุดที่ไม่ต้องการให้มี span ครอบ เช่น <title>, <meta> หรือ <style> เป็นต้น
ใช้ Label เมื่อ
  • สร้าง label สำหรับ input ต่างๆ
  • สร้างข้อความที่ต้องการเปลี่ยนแปลงสไตล์
ส่วนตัวแล้ว แนะนำให้หลีกเลี่ยงการใช้งาน Label เพราะผลลัพธ์มันเปลือง และน่าเกลียดกว่า
ความจริงแล้วยังมีคอนโทรลอีกหนึ่งตัวที่ทำหน้าที่เหมือน Literal คือLiteralControl ข้อแตกต่างของสองคอนโทรลนี้คือ LiteralControlจะไม่เก็บข้อมูลไว้ใน ViewStateทำให้ค่าของพร็อพเพอร์ตีย์ต่างๆไม่ถูกจำข้าม Request

Sunday, September 11, 2011

String Format for Double [C#]


The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.
[C#]
// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.
[C#]
// max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.
[C#]
// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567);      // "123.5"
String.Format("{0:00.0}", 23.4567);       // "23.5"
String.Format("{0:00.0}", 3.4567);        // "03.5"
String.Format("{0:00.0}", -3.4567);       // "-03.5"

Thousands separator

To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.
[C#]
String.Format("{0:0,0.0}", 12345.67);     // "12,345.7"
String.Format("{0:0,0}", 12345.67);       // "12,346"

Zero

Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).
Following code shows how can be formatted a zero (of double type).
[C#]
String.Format("{0:0.0}", 0.0);            // "0.0"
String.Format("{0:0.#}", 0.0);            // "0"
String.Format("{0:#.0}", 0.0);            // ".0"
String.Format("{0:#.#}", 0.0);            // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not indouble.ToString method). To align numbers to the left use negative number of spaces.
[C#]
String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567);   // "123.5     "
String.Format("{0,10:0.0}", -123.4567);   // "    -123.5"
String.Format("{0,-10:0.0}", -123.4567);  // "-123.5    "

Custom formatting for negative numbers and zero

If you need to use custom format for negative float numbers or zero, use semicolon separator;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.
[C#]
String.Format("{0:0.00;minus 0.00;zero}", 123.4567);   // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567);  // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0);        // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.
[C#]
String.Format("{0:my number is 0.0}", 12.3);   // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3);          // "12aaa.bbb3"


ref : http://www.csharp-examples.net/string-format-double/

String Format for Int [C#]


Integer numbers can be formatted in .NET in many ways. You can use static method String.Format or instance method int.ToString. Following examples shows how to align numbers (with spaces or zeroes), how to format negative numbers or how to do custom formatting like phone numbers.

Add zeroes before number

To add zeroes before a number, use colon separator „:“ and write as many zeroes as you want.
[C#]
String.Format("{0:00000}", 15);          // "00015"
String.Format("{0:00000}", -15);         // "-00015"

Align number to the right or left

To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.
[C#]
String.Format("{0,5}", 15);              // "   15"
String.Format("{0,-5}", 15);             // "15   "
String.Format("{0,5:000}", 15);          // "  015"
String.Format("{0,-5:000}", 15);         // "015  "

Different formatting for negative numbers and zero

You can have special format for negative numbers and zero. Use semicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.
[C#]
String.Format("{0:#;minus #}", 15);      // "15"
String.Format("{0:#;minus #}", -15);     // "minus 15"
String.Format("{0:#;minus #;zero}", 0);  // "zero"

Custom number formatting (e.g. phone number)

Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.
[C#]
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551);       // "89-5871-2551"


ref : http://www.csharp-examples.net/string-format-int/

String Format for DateTime [C#]


String Format for DateTime [C#]

This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.

Custom DateTime Formatting

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed),t (P.M or A.M) and z (time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
[C#]
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator andDateTimeForma­tInfo.TimeSepa­rator.
[C#]
// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:
[C#]
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.
Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
SpecifierDateTimeFormatInfo propertyPattern value (for en-US culture)
tShortTimePatternh:mm tt
dShortDatePatternM/d/yyyy
TLongTimePatternh:mm:ss tt
DLongDatePatterndddd, MMMM dd, yyyy
f(combination of D and t)dddd, MMMM dd, yyyy h:mm tt
FFullDateTimePatterndddd, MMMM dd, yyyy h:mm:ss tt
g(combination of d and t)M/d/yyyy h:mm tt
G(combination of d and T)M/d/yyyy h:mm:ss tt
mMMonthDayPatternMMMM dd
yYYearMonthPatternMMMM, yyyy
rRRFC1123Patternddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
sSortableDateTi­mePatternyyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
uUniversalSorta­bleDateTimePat­ternyyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
[C#]
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime

reference : http://www.csharp-examples.net/string-format-datetime/

String.Format("{0}", "formatting string"};


One of the painful things about good old ASP was string formatting, VBScript simply didn't have anything useful. C# (and VB.Net) do, but MSDN doesn't provide a quick reference to the formatting options. So here's a quick reference.
To compare string formatting in C# to those in C lets have an example,
char szOutput[256];
sprintf(szOutput, "At loop position %d.\n", i);


sprintf takes an output buffer, a format string and any number of arguments to substitute into the format string.
The C# equivalent for sprintf is String.Format, which takes a format string and the arguments. It returns a string, and because you're not passing in a buffer there's no chance of a buffer overflow.
string outputString = String.Format("At loop position {0}.\n", i);

So why doesn't have the format argument have parameters specifying what data type you're formatting? The CLR objects have metadata which informs the CLR what the objects are, and each object has a standard ToString() method which returns a string representation of that object. Much nicer than C where if you passed the wrong type of variable into sprintf everything could come crashing down.
The ToString method can accept a string parameter which tells the object how to format itself. In the call to String.Format , the formatting string is passed after the position, for example, "{0:##}". The text inside the curly braces is {argumentIndex[,alignment][:formatString]}. If alignment is positive, the text is right-padding to fill the specified field length, if it's negative, it's left-padded.

formatting strings

There's not much formatting that can be applied to a string. Only the padding / alignment formatting options can be applied. These options are also available to every argument, regardless of type.
exampleoutput
String.Format("--{0,10}--", "test");--      test--
String.Format("--{0,-10}--", "test");--test      --

formatting numbers

Number formatting is culture dependant. For example, formatting a currency string on my laptop will return a result like £9.99, formatting a currency on a machine set for the US region would return $9.99.
specifiertypeformatoutput
(double 1.2345)
output
(int -12345)
ccurrency{0:c}£1.23-£12,345.00
ddecimal
(whole number)
{0:d}System.FormatException-12345
eexponent / scientific{0:e}1.234500e+000-1.234500e+004
ffixed point{0:f}1.23-12345.00
ggeneral{0:g}1.2345-12345
nnumber{0:n}1.23-12,345.00
rround trippable{0:r}1.23System.FormatException
xhexadecimal{0:x4}System.FormatExceptionffffcfc7

custom number formatting

specifiertypeformatoutput
(double 1234.56)
0zero placeholder{0:00.000}1234.560
#digit placeholder{0:#.##}1234.56
.decimal point placeholder{0:0.0}1234.6
,thousand separator{0:0,0}1,235
%percentage{0:0%}123456%

In addition there is the group separator; this is useful for varying the format, depending on the value of the parameter passed. For example
String.Format("{0:£#,##0.00;(£#,##0.00);Nothing}", value);

This will output "£1,240.00" if passed 1243.56.  It will output the same format bracketed if the value is negative "(£1,240.00)", and will output the string "Nothing" if the number is zero.

date formatting

Date formats are very dependant on the culture information passed. The examples below are shown using the UK culture.
specifiertypeoutput
(June 8, 1970 12:30:59)
dShort Date08/06/1970
DLong Date08 June 1970
tShort Time12:30
TLong Time12:30:59
fFull date and time08 June 1970 12:30
FFull date and time (long)08 June 1970 12:30:59
gDefault date and time08/06/1970 12:30
GDefault date and time (long)08/06/1970 12:30:59
MDay / Month8 June
rRFC1123 date stringMon, 08 Jun 1970 12:30:59 GMT
sSortable date/time1970-06-08T12:30:59
uUniversal time, local timezone1970-06-08 12:30:59Z
YMonth / YearJune 1970

custom date formatting

specifiertypeoutput
(June 8, 1970 12:30:59)
ddDay08
dddShort Day NameMon
ddddFull Day NameMonday
hh2 digit hour12
HH2 digit hour (24 hour)12
mm2 digit minute30
MMMonth06
MMMShort Month nameJun
MMMMMonth nameJune
ssseconds59
ttAM/PMPM
yy2 digit year70
yyyy4 digit year1970
:seperator, e.g. {0:hh:mm:ss}12:30:59
/seperator, e.g. {0:dd/MM/yyyy}08/06/1970

There are others, including time zone formatting and so on, but the ones above are the most commonly used.

culture information

string.format also provides a method which accepts a CultureInfo argument, as an IFormatProvider. This is important when trying to write portable and localisable code, as, for example, month names will change according to the local culture of the machine you are running on. Rather than simply call the standard String.Format you should consider always calling the overloaded culture method. If you don't need to specify a culture you can use the System.Globalization.CultureInfo.InvariantCulture. This will then default your formatting to English, as opposed to the culture of the current thread.