C# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
C# etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

String Format for Double [C#]

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.

// 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.##“.

// 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.

// 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.

String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"

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).

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 in double.ToString method). To align numbers to the left use negative number of spaces.

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.

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“.

String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"

Visual Studio CSharp - Exception tips?

You can catch the type 'Exception' and EVERY exception will be caught. If you want to handle multiple exceptions in a different way, you could catch specific exceptions.
For example
try{ ... }
catch(FileNotFoundException ex)
{ // add some code that will create a default file }
catch(ArgumentException ex)
{ // add different code to handle this exception }
catch(Exception ex)
{ // do something with the rest of the exceptions }

In the above example, if a FileNotFoundException occurs, the first catch clause will run, and if some unknown exception occurs that you didn't see coming, it will be caught in the last clause (Exception ex).

Clear Cookie in ASP.NET

Delete all cookies:


Dim i As Integer
Dim cookieName As String
Dim limit As Integer = Request.Cookies.Count - 1
For i = 0 To limit
aCookie = Request.Cookies(i)
aCookie.Expires = DateTime.Now.AddDays(-1)


private int i;
private string cookieName;
private int limit = Request.Cookies.Count - 1;
for (i = 0; i <= limit; i++)
aCookie = Request.Cookies[i];
aCookie.Expires = DateTime.Now.AddDays(-1);

How to create and write to a browser cookie in ASP.NET using C#

1- Go to the code-behind of the .aspx page you wish to create the browser cookie from. I will show 2 approaches on creating such a cookie.
2- Method 1:

// A cookie called "userInfo" is dynamically created and the key "userName" is assigned the value "patrick".
Response.Cookies["userInfo"]["userName"] = "patrick";
// A new key called "lastVisit" is added to the collection of values in the cookie and assigned the current datetime value.
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
// The expiration value of the cookie is set to 1 day in the future from the current date.
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
3- Method 2:

HttpCookie aCookie = new HttpCookie("userInfo");
// The key "userName" is added to the cookie and assigned the value "patrick" as the above example.
aCookie.Values["userName"] = "patrick";
// The key "lastVisit" is added to the cookie and assigned the current datetime value.
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
// The expiration date of the cookie is set to 1 day in the future from the current date.
aCookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie to the browser cookie collection.

CSharp: How to fix following C# error in Visual Studio: Cannot apply indexing with [] to an expression of type 'System.Data.DataTable'

Cannot apply indexing with [] to an expression of type 'System.Data.DataTable'

string variable = Table[0][1].ToString();

DataTable Table;string variable = Table.Rows[index][column-index].ToString();


DataTable Table;
string variable = Table.Rows[0][1].ToString();

The above error happens when you try to index the datatable without first accessing the "Rows" property. You must first access the "Rows" property and then provide the index.

How to read the first sheet in Excel with C#

string AppPath=Request.ServerVariables["APPL_PHYSICAL_PATH"]+"Tahsilat/";
OleDbConnection m_ConnectionToExcelBook;
OleDbDataAdapter m_AdapterForExcelBook;
m_ConnectionToExcelBook = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+AppPath+"deneme.xls;Extended Properties=Excel 8.0;");
bool ErrorExist=false;


DataTable dtExcelSchema = m_ConnectionToExcelBook.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// select first sheetname
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
DataTable DataObject = new DataTable();
OleDbCommand selectCommand = new OleDbCommand("select * from [" + sheetName + "]");

selectCommand.Connection = m_ConnectionToExcelBook;
m_AdapterForExcelBook = new OleDbDataAdapter();
m_AdapterForExcelBook.SelectCommand = selectCommand;

if (DataObject.Rows.Count > 0)

Adding TextBox Values using Javascript in C#

The following code sample shows how to add the textbox values using javascript.

The keyup event of the textbox is used. Three textboxes is use , the functionality is to add the first and second textboxes and total in third textbox.

Step 1-The Javascript Function follows :

function KeyUpEvent()
var txt1 = document.getElementById("txt1");
var txt2 = document.getElementById("txt2");
var txt3 = document.getElementById("txt3");
if ((txt1.value != "") && (txt2.value != ""))
txt3.value = parseInt(txt1.value) + parseInt(txt2.value);

Step 2-Design

Step 3-To add attributes to the textbox at code behind use this example:

txt1.Attributes.Add("onKeyUp", "javascript:KeyUpEvent();");
txt2.Attributes.Add("onKeyUp", "javascript:KeyUpEvent();");

Arrays in C#

Arrays are a special type, built into C#, that holds a group of other types. Arrays are a useful construct for organizing data. They provide matrix support and, even further, multidimensional support. As a collection, an array allows going beyond simple storage of data and provides fundamental discovery and manipulation of that data. Array methods are discussed in the next chapter. This chapter shows declaration and instantiation of single-dimension, multidimension, and jagged arrays.

Single-Dimension Arrays
Single-dimension arrays provide the capability to store and manipulate a list of items. Every element is of the same type. This is how such an array should be declared:
Type[] Array-Identifier [initializer] ;
The array identifier is any valid identifier. It should be meaningful for the purpose of the array. The optional initializer allocates memory for the array.
Once a C# array has been initialized, it can't change its size. If dynamic resizing of an array is needed, use one of the collection classes.
Here are some examples of single-dimensional array declarations:
// uninitialized declaration
MyClass[] myArray;
byte[] inputBuffer = new byte[2048];

// creates an array of 3 strings
string[] countStrings = { "one", "two", "three" };
Arrays may be declared with no initialization. Remember, an array must be initialized before it's used. It may be initialized with an integer type value inside the brackets of the initializer, as the following example shows:
// creates an array of 3 strings
string[] countStrings = new string[3] { "one ", " two", " three" };

Another way to initialize an array is by leaving the space in the brackets of the initializer blank and then following the initializer brackets with an initializer list in braces. The array initializer list is a comma-separated list of values of the array type. The size of the array becomes the number of elements in the initializer list. If an integer value is added to the initializer brackets and there is an initializer list in the same array initializer, make sure that the integer value in the initializer brackets is greater than or equal to the number of elements in the initializer list. Take a look at this code sample:
// error
string[] countStrings = new string[3] { "one", "two", "three", "four" };
The initializer in this code fails with an error because the allocated size of the countStrings array is only 3, but the number of strings in the list is four. The number of strings in the list can't exceed the allocated size.

Don't specify a size when using an initializer list on an array. Later, it will be easier to add an item to the list and avoid the mistake of not incrementing the number.

Dimensional Arrays
Multidimensional arrays are similar in declaration and initialization to single-dimensional arrays, with a few exceptions. For every new dimension included, add a comma to brackets of the array declaration. During initialization, add an integer value to each of the dimensions specified in the declaration. Here are a couple examples:
long [ , ] determinant = new long[4, 4];
int [ , , ] stateSpace = new int[2, 5, 4];
bool [ , ] exclusiveOr
= new bool[2, 2] { {false, true}, {true, false} };
Remember, the integer values in the initializer brackets are optional when including an initializer list.

Jagged Arrays
Jagged arrays allow creation of multidimensional arrays without the requirement of making every element of every dimension the same size. If an application has data that doesn't cover the entire range of possible values, this may be an option. It may also open the opportunity to save memory space. Here are some examples:
decimal[][] monthlyVariations = new decimal[12][];

monthlyVariations[(int)Months.Jan] = new decimal[31];
monthlyVariations[(int)Months.Feb] = new decimal[28];
monthlyVariations[(int)Months.Dec] = new decimal[31];

MS SQL 2014 üzerinde "The transaction log for database is full due to LOG_BACKUP" hatası ve çözümü

         Genellikle çoklu silme işlemlerinden kaynaklanan ve kapatılmayan transaction'ların LOG dosyasını büyütmesinden dolayı "Th...