Pages

Jul 12, 2010

How to show date alone in GridView BoundField when using DateTime as DataType in DataBase.


DateTime Formatting in GridView:
Usually we create a field with DataType DateTime in Database 
say for eg. MSAccess database.
Now when you show this in the GridView it shows Date along with 
time like 7/6/2010 8:10:12 PM
But you may be in situation to show only the Date alone.
like 7/6/2010
To do so, simple specify the format in the GridView BoundField like

<Columns>
    <asp:BoundField 
              DataField="Date1" 
              HeaderText="Date" 
              DataFormatString="{0:d}" />
</Columns>

Refer the below link for different other formats
http://msdn.microsoft.com/en-us/library/
system.web.ui.webcontrols.boundfield.dataformatstring.aspx

Jul 10, 2010

How to show a alert message or confirmation when deleting row from GridView without postback + Asp.Net

This is a basic logic needed in Grid-view while deleting a data. By mistake people may click
on the delete button and if there is no alert or confirmation, some valuable data may be lost.
Let's go for implementation, below is the grid-view


<asp:GridView ID="GridView2" runat="server"  AutoGenerateSelectButton="true"
            DataKeyNames="ID"  AutoGenerateDeleteButton="true"
            onrowdatabound="GridView2_RowDataBound" >
      <Columns>
                <asp:BoundField DataField="ID" HeaderText="SL.No" Visible="false"/>
                <asp:BoundField DataField="Project" HeaderText="Project" Visible="false"/>
      </Columns>
</asp:GridView>

In the above grid the two properties namely AutoGenerateSelectButton,
and AutoGenerateDeleteButton let you show the Select and
Delete button on the GridView.
Now on onrowdatabound event of the GridView we implement the logic like


  protected void GridView2_RowDataBound(object sender,
                                                            GridViewRowEventArgs e)
    {
        // Gets the Delete command column, which is the first column
        foreach (Control control in e.Row.Cells[0].Controls)
        {
            // Gets the Delete link button
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
               DeleteButton.OnClientClick =
               "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }
The above code will show you an alert message before deleting a row.

How to access ServerSide method from GridView's ItemTemplate

Calling a CodeBehind Method From GridView's ItemTemplate:


While working with GridView, there may be a case where 
we actually need to do some operations in serverside for 
which we may be in a need to call a server side
method from ItemTemplate of a GridView.


Say for example, 
I had a situation where i need to call a server side 
method (which return a string value) from ItemTemplate.
So i used a label in the ItemTemplate like 



<asp:TemplateField HeaderText="Testing">
<ItemTemplate>
<asp:Label ID="lblCustomerAge" Text='<%# GetCategory() %>' runat="server">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>


Here GetCategory is the server side method.Code-behind is given below

  protected string GetCategory()
    {
       // Do whatever you want here
        return "TestCategory"; // For eg. passing a string
    }

Jul 6, 2010

How to split a sentence into word using C# + Regular Expressions


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string[] w = SplitWords("This is a Sample, Test");
        foreach (string s in w)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }

    /// <summary>
    /// Get all the words in the input string and separate them.
    /// </summary>
    static string[] SplitWords(string s)
    {
        //
        // Split on all non-word characters.
        // ... Returns an array of all the words.
        //
        return Regex.Split(s, @"\W+");
        // @      special verbatim string syntax
        // \W+    one or more non-word characters together
    }
}
Output:
This
is
a
Sample
Test

Jul 3, 2010

How to find the System Name in C#

Lets make use of the Namespace 
using System.Security.Principal; to find the System name.


Below is the code:
lblSysNo.Text = WindowsIdentity.GetCurrent().Name.ToString();

Jul 1, 2010

How to pass double couted paramaters to Command line utilities programatically + c#

Invoking a Command Line Utility From C#:


For eg. let's consider FWTools which has a command line utility named 
ogr2ogr for converting tab to kml
Below is the code to invoke the command line utility ogr2ogr

Invoking Command Line without parameters:

// Create an instance for System.Diagnostic.Process
Process proc = new Process();
// Provide the utility name with location
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
// Start the process
proc.Start();

Invoking Command Line with normal parameters:
Note: -f, KML, sourcepath, destpath are arguments separted by space
Process proc = new Process(); 
string driver = @"-f KML C:\FWTools2.4.7\bin\zeeee.kml 
C:\FWTools2.4.7\bin\Morocco.tab"
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.Arguments = driver; 
proc.Start();
proc.WaitForExit(); // use if you want your  program to wait for the process to complete.
proc.Close();

Invoking Command Line with Double couted parameters:

Usually space in the arguments list denote that each are separate
argument separated by space.

In the above code KML is the name of the driver used to convert 
Tab to KML.

And to convert ESRI's shape file to MapInfo's Tab file the driver 
used is "MapInfo File", which itself has a space

so by default command line arguments will consider it as a
two parameter one is "MapInfo" and other is "File"
so the program goes wrong.

Below is the solution, how to pass the double couted paremeter

string driver = "-f " + @"""" + "MapInfo File" + @"""" +
 @" C:\FWTools2.4.7\bin\test.tab C:\FWTools2.4.7\bin\test.shp";

By using this methodology, we can pass "MapInfo File" as a 
single argument to a command line utility.