C# has a static constructor for this purpose. static class YourClass { static YourClass() { // perform initialization here } } A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or […]
Category: C#
How to create the ShowBlanksValue and ShowNonBlanksValue items in Devex Grid
By design, GridViewDataComboBoxColumn does not render (Blank) and (NonBlank) items if the HeaderFilterMode property is set to CheckedList. However, you can add these items in the HeaderFilterFillItems event handler. Just call the FilterValue.CreateShowBlanksValue and FilterValue.CreateShowNonBlanksValue methods. <dx:ASPxGridView ID=”grid” runat=”server” AutoGenerateColumns=”False” DataSourceID=”dsCategories” KeyFieldName=”CategoryID” OnHeaderFilterFillItems=”grid_HeaderFilterFillItems”> <Columns> <dx:GridViewDataTextColumn FieldName=”CategoryID”> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName=”Description”> </dx:GridViewDataTextColumn> <dx:GridViewDataComboBoxColumn FieldName=”CategoryNameNull” Caption=”Category Name”> <Settings HeaderFilterMode=”CheckedList” /> <PropertiesComboBox DataSourceID=”dsCategories” ValueField=”CategoryNameNull” TextField=”CategoryNameNull” /> </dx:GridViewDataComboBoxColumn> </Columns> […]
How to add default value for Entity Framework migrations for DateTime and Bool
Just add defaultValue parameter in CreateTable method for property: public partial class TestSimpleEntity : DbMigration { public override void Up() { CreateTable( “dbo.SimpleEntities”, c => new { id = c.Long(nullable: false, identity: true), name = c.String(), deleted = c.Boolean(nullable: false, defaultValue: true), }) .PrimaryKey(t => t.id); } public override void Down() { DropTable(“dbo.SimpleEntities”); } } After that, run update-database -verbose command, […]
String Interpolation, String Format, String Concat and String Builder in C#
We will try to return a string like: “I can text whatever I want with 4 different options in C#. ” with String Interpolation, String Format, String Concat, and String Builder. public class StringOptions { private string data1 = “4”; private string data2 = “C#”; public string StringInterpolation() => ($”I can text whatever I want […]
How to make the default class type ‘public’ instead of ‘internal’ in Visual Studio
VS2012: C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class VS2015: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class VS2017(RC): C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class VS2017(Professional): C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class VS2019 (Enterprise): C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.cs VS2019 (Professional): C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class\Class.cs Starting with Visual Studio 2022 VS is a 64 bit application, meaning the item templates are in C:\Program Files\… instead of C:\Program Files […]
How to get value from resx file in C#
// Gets the value of associated with key “MyKey” from the local resource file (“~/MyPage.aspx.en.resx”) or from the default one (“~/MyPage.aspx.resx”) //The default location for resx files is App_LocalResources object keyValue = HttpContext.GetLocalResourceObject(“~/MyPage.aspx”, “MyKey”);
How to lock the ciritical code part in C#
According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released. The lock keyword calls Enter at the start of the block and Exit at the end of the block. lock keyword actually […]
Add default value to Devex Grid Columns in C#
protected void grid_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e) { e.NewValues[“BirthDate”] = new DateTime(1970, 1, 10); e.NewValues[“Title”] = “Sales Representative”; } Here is the result:
Pass model from Razor view to JavaScript
Let’s say you send a model called “MyModel” from controller to view. In Controller: … var result = new MyModel() { Id = 1, Name = “Ercan”, FavoriteTeam = “Galatasaray”, FavoriteGame = “Half Life Series” } return View(result); … and now we will send this model which comes with result to Javascript via setName function: […]
Change some value inside List
Let’s say you have a List of T. And there are Property1, Property2, Property3 in T. If you want to change the value of Property2 in T then you can use: var myList = List<T>; foreach (var item in myList) { item.Property2 = newValue; } or var myList = List<T>; myList.ForEach(x => x.Proprty2 = newValue); […]
How to use SQL RAISEERROR() messages in C#
DECLARE @MyValue int SELECT @MyValue = Column1 WHERE Column2 > 50 IF @MyValue IS NULL BEGIN RAISEERROR(‘This is my custom message from SQL.’, 16, 1) END ELSE SELECT MyValue END Use an error code within 11-16, or just use 16 for a “general” case. RAISERROR(‘This is my custom message from SQL.’,16,1) Why? Here’s summary of […]
IndexOf() and LastIndexOf() in C#
The IndexOf() method returns the index number of the first matched character whereas the LastIndexOf() method returns the index number of the last matched character. using System; public class StringExample { public static void Main(string[] args) { string s1 = “Hello C#”; int first = s1.IndexOf(‘l’); int last = s1.LastIndexOf(‘l’); Console.WriteLine(first); Console.WriteLine(last); } } Output: […]
How to Validate a DateTime in C#?
DateTime myDate; if(DateTime.TryParse(txtBirthDate.Text, out myDate)) { //Valid Date } else { //Invalid Date }
Convert comma separated string into a List in C#
string myList = “9,3,12,43,2”; List<int> intList = myList.Split(‘,’).Select(int.Parse).ToList();
Converting a List to a comma separated string in C#
List<int> list = new List<int>() {1,2,3}; string.Join<int>(“,”, list) Join has generic overloads. It is so much easier to use it in that way to convert your list to the different types.
How to add placeholder to Multiple Selection DropDownList in Asp.Net MVC
@Html.ListBox( “Countries”, ViewBag.AllCountries as MultiSelectList, new { @class = “form-control”, data_placeholder = “Choose a Country…” } )
Convert List to List in one line in C#
string sNumbers = “1,2,3,4,5”; var numbers = sNumbers.Split(‘,’).Select(Int32.Parse).ToList();
Checking multiple contains on one string
new[] {“,”, “/”}.Any(input.Contains) or you can use Regex Regex.IsMatch(input, @”[,/]”);