Sunday, September 29, 2013

How to Put CheckBoxes Dynamically in Data GridView of Window Application

Step 1: Write the Following code in the binding event of data GridView
 

DataGridViewCheckBoxColumn chbx_Column = new DataGridViewCheckBoxColumn();
chbx_Column.Name = "chk_column";
chbx_Column.HeaderText = "";
chbx_Column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridView1.Columns.Add(chbx_Column);

 //Select cell where checkbox to be display
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(0, -1, true);            //0 Column index -1(header row) is row index

//Mention size of the checkbox
chkbox.Size = new Size(18, 18);
//set position of header checkbox where to places
rect.Offset(40, 2);
 chkbox.Location = rect.Location;

chkbox.CheckedChanged += chkBoxChange;

//Add CheckBox control to datagridView
this.dataGridView1.Controls.Add(chkbox);

// for adding combo box in header
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(0, -1, true);            //0 Column index -1(header row) is row index
ComboBox c = new ComboBox();
c.BackColor = Color.FromArgb(246, 246, 246);
c.Size = new Size(100,15);
rect.Offset(0, 0);
c.Location = rect.Location;
this.dataGridView1.Controls.Add(c);
Step 2: For individual row ,write event code. This is just to uncheck the checked row and check the unchecked row
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
     ifConvert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells["chk_column"].Value)== true)
           
     {
         dataGridView1.Rows[e.RowIndex].Cells["chk_column"].Value =false;
     } 
     else     {
        dataGridView1.Rows[e.RowIndex].Cells["chk_column"].Value = true;
     }
}

How to Get n no. of Rows From DataTable

Just write a small piece of code and get n no. of rows from datatable.
 
Syntax
 
DataTable newTable=new DataTable();
newTable= oldTable.AsEnumerable().Take(10).CopyToDataTable();
 
Suppose you have 100 of rows in oldTable. Using above line of code you will get 10 rows in newTable.
 
you can replace 10 with your number and easily get no. of rows which you want.

DateTime Start and End of Day Extension Methods

Another quick post with some useful extension methods for the System.DateTime struct. . One particular use case has been to pass a "start" and an "end" DateTime to some SQL Server stored procedure. The stored procedure then returns some data based on some timestamp field that falls between the start and end DateTime's passed in. 

In the code I was maintaining, the previous developer had created a DateTime value using DateTime.Now, which returns a DateTime with the time part also populated to the current system time. So when passing this DateTime to the stored proc as a "start" DateTime, the proc was looking from the time-part onwards on the specific day represented by the DateTime. Likewise, when using a similarly created DateTime for the "end" DateTime, the stored proc only returned rows upto the time-part. This was undesired behaviour because the original intention was to retrieve all of the records between two specified days (inclusive of the start and end days). 

I decided to tackle this at the application-level. This was mainly to keep the stored procedure flexible so that it can continue to handle retrieval of records at the more granular time level if required. I decided to implement this functionality by adding two extension methods on DateTime, namely, ResetTimeToStartOfDay and ResetTimeToEndOfDay. These return new DateTime values with the time part appropriately set. The idea is to call ResetTimeToStartOfDay on the "start" DateTime and ensure that the returned DateTime is sent to the stored procedure. Likewise, call ResetTimeToEndOfDay on the "end" DateTime. I've included the implementation of the two methods below - very simple but useful to have in your library. 

public static DateTime ResetTimeToStartOfDay(this DateTime dateTime)
{
   return new DateTime(
      dateTime.Year, 
      dateTime.Month, 
      dateTime.Day, 
      0, 0, 0, 0);
}

public static DateTime ResetTimeToEndOfDay(this DateTime dateTime)
{
   return new DateTime(
      dateTime.Year, 
      dateTime.Month, 
      dateTime.Day, 
      23, 59, 59, 999);
}

C#/.NET Features You May Not Know About

I thought it would be useful to document some of the typically lesser known features of the C# programming language . Some of these features I've found useful and others I probably just haven't found a suitable use case for yet. 

1. Anonymous Code Scopes in Methods

It's possible to have anonymous inner scopes within your method definitions. 
void MethodWithAnonymousScope()
{
    var helloPart = "Hello";

    {
        var worldPart = "world";
        Console.WriteLine("{0} {1}", helloPart, worldPart);
    }

    // "worldPart" doesn't resolve in this scope
}

2. Increment/Decrement Operator Position Significance

The position of the increment (++) and decrement (--) operators is significant. In the example below, when the increment operator is used as a postfix, it returns the value of 'number' before it has been incremented. Conversely, the prefix increment operator returns the value after it has been incremented. The decrement operator works with the same logic but decrements the number.
void PlusPlusOperator()
{
    var number = 0;

    Console.WriteLine(number++); // Outputs zero
    Console.WriteLine(++number); // Outputs two
}

3. The Default Keyword

The default keyword is a neat way to get the default value for a specified type. It's especially useful when working in a generic context. 
void DefaultKeyword()
{
    var intDefault = default(int); // default(int) == 0
    var boolDefault = default(bool); // default(bool) == false

    // default(string) == null (as for all reference types)
    var stringDefault = default(string);
}

4. Null-Coalescing Operator

The null-coalescing operator (??) provides a succinct way of returning a default value if your reference or nullable-value type is null. In the following example, if myNullableInteger (left operand) is not null, then it's returned, else the default value for int is returned (right operand). 
int NullCoalescingOperator()
{
    int? myNullableInteger = SomeMethodThatCouldReturnNull();
    return myNullableInteger ?? default(int);
}

5. Short-Circuit Evaluation with Boolean Operators

The logical AND (&&) and OR (||) operators are short-circuit evaluated (left to right). For example, if the left operand of a logical AND is false, the right operand is not evaluated (as the whole condition will always be false). Similarly, if the left operand of a logical OR is true, the right operand is not evaluated. This can be demonstrated by observing the output of: 
void ShortCircuitEvaluation()
{
    bool result;
           
    result = LeftOperand(true) || RightOperand(false);
    result = LeftOperand(false) || RightOperand(true);
    result = LeftOperand(true) && RightOperand(false);
    result = LeftOperand(false) && RightOperand(true);
}

bool LeftOperand(bool value)
{
    Console.WriteLine("Left operand evaluated");
    return value;
}

bool RightOperand(bool value)
{
    Console.WriteLine("Right operand evaluated");
    return value;
}
It's useful to know this so that you can safely perform multiple tests in a single if statement. In the example below, if myObject is null, the right operand is not evaluated (which is good because it'd cause a NullReferenceException). 
if (myObject != null && myObject.SomeProperty == SomeValue)
    ...
Also note that if you use a single '&' and single '|' you bypass short-circuit evaluation and force the entire condition to be evaluated. 

6. Aliases for Generic Types

You can assign an alias to a namespace but you can also assign an alias to a specific generic type to save yourself from typing the awkward generic syntax over and over again (especially useful when working with key/value pair based generic types where the value may also be a key/value pair!). 
using StringList = System.Collections.Generic.List<string>;
...
void GenericAliases()
{
    // Can use the alias "StringList"
    // instead of List<string> 

    var stringList = new StringList();
    stringList.Add("Hello");
    stringList.Add("World");
    stringList.ForEach(Console.WriteLine);
}

7. Extension Methods on Dynamic Types

 As the title states, you cannot invoke an extension method on a type (that has the extension method defined for it and is in scope) which is dynamically typed. I have documented this one in this post (click to view). As the post shows, you have to call your extension method in the same fashion as you would call a standard static method, then pass your dynamically typed variable in as a parameter to the extension method. 

8. System.String supports an Indexer

The string class has a readonly (get) char indexer defined on it, thus allowing you to access characters in the string using a zero-based index. 
void StringIndexer()
{
    string message = "Hello, world!";

    for (int i = 0; i < message.Length; i++)
    {
        Console.WriteLine(message[i]);
    }
}

9. Using foreach with System.String

The string class implements the 
IEnumerable&lt;char&gt; interface, which means that you can use the foreach statement on a string to enumerate through each character. 
void ForeachWithString()
{
    string message = "Hello, world!";

    foreach (char character in message)
    {
        Console.WriteLine(character);
    }
}

10. Introspecting Code with Expression Trees

The System.Linq.Expressions.Expression class enables you to represent a code expression in a tree-based data structure that can then be used for introspection. This is a powerful feature which also then enables code modification in the expression tree (at runtime) and then subsequent compilation and execution. 

The following example shows how we can wrap a simple lambda expression into an Expression, introspect the expression, compile the expression (in this case returning a 
Func&lt;int, int, int&gt;) and then execute the expression.
void Expressions()
{
    Expression<Func<intintint>> addExpression = (a, b) => a + b;

    foreach (var param in addExpression.Parameters)
    {
        Console.WriteLine(
            "Func Param Name: {0}, Param Type: {1}",
            param.Name,
            param.Type);
    }

    Console.WriteLine("Func return type: {0}",
        addExpression.ReturnType);

    Console.WriteLine("10 + 20 = {0}",
        addExpression.Compile()(10, 20));
                       
    // Can also use the Invoke method on the returned Func<...>
    // to aid readability
    // e.g. addExpression.Compile().Invoke(10, 20);
}