Thursday 22 August 2013

Alternate Color Rows in Gridview based on some condition

To show the alternate color to the rows, there is an attribute alternate template in gridview which gives the alternate color, but if the alternate color depends on the data value in the gridview then we need to write the logic accordingly. I have a gridview which is having month wise-weekly data. now weeks in a month varies, I needed to show the color change of alternate month.

the gridview is bind as usual, with data from the database table which is being fetched using ADO.net into the dataset and then bind with the gridview.

next comes the logic to change the alternate color:

private void BindGrid()
{

SqlConnection con = new SqlConnection("Data Source=datasource ;user id=sa;password=password;Initial Catalog=databasename");
con.Open();

SqlDataAdapter sda = new SqlDataAdapter("select * from TableName con);sda.Fill(ds);
ViewState[
"Dataset"] = ds;gvClarityCalendar.DataSource = ds.Tables[0];
gvClarityCalendar.DataBind();
//change the color of the rows
SetRowBackColor(gvClarityCalendar);
con.Close();
}


public void SetRowBackColor(GridView gv)
{
  string strPreviousDataKeyValue = "";
System.Drawing.
Color RowColor = System.Drawing.Color.PaleGoldenrod;
foreach (GridViewRow row in gv.Rows){

if (!strPreviousDataKeyValue.Equals(gv.Rows[row.RowIndex].Cells[0].Text.ToString()))RowColor = RowColor == System.Drawing.
Color.AliceBlue ? System.Drawing.Color.PaleGoldenrod : System.Drawing.Color.AliceBlue;gv.Rows[row.RowIndex].BackColor= RowColor;
strPreviousDataKeyValue = gv.Rows[row.RowIndex].Cells[0].Text.ToString();
}





In the above figure, we can see the color is alternate according to the data,here it is accirding to the name of the month.

Wednesday 29 May 2013

use of Constructors and Static Keyword

The type of Constructor and their use are clearly defined over here  :

http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C
The study of constructor leads me to the importance of Static classes, methods and variables, which was cleared from here :

http://www.codeproject.com/Articles/15269/Static-Keyword-Demystified

thanks.

Monday 27 May 2013

Types of Authentication in ASP

Authentication in ASP.NET

Having read the previous section, you should have a good idea of the options available for authentication under JSP. Most likely, you have already used or at least encountered one or more of the JSP authentication schemes in your experience as a JSP developer. With those options in mind, we will now discuss authentication procedures in ASP.NET, including what options are available, differences and similarities between ASP.NET authentication and JSP authentication, and several different ways of authenticating users under ASP.NET.
In this topic, we will discuss four forms of authentication, each of which has its advantages and disadvantages:
  • Windows authentication, which is controlled and executed by IIS and is useful mainly for intranet Web applications.
  • Basic authentication, which is an insecure protocol controlled and executed by IIS but can be used by Internet applications that do not require security or use additional security methods such as SSL.
  • Form-based authentication, which is extremely similar to the form-based authentication we discussed in the JSP Authentication section at the beginning of this document. We will attempt to use these similarities to make learning ASP.NET authentication pages easier.
  • Passport authentication, which uses Microsoft's Passport Web service to authenticate the user.

Windows Authentication

Windows authentication, also called Integrated Windows authentication, uses Windows operating system accounts to verify a user's credentials. This means that the user must either be logged in to the domain on which the server is running (in which case they will not be queried for credentials), or must log in to the domain when they try to access a protected page. This authentication scheme is part of IIS, and must be configured and executed by IIS; it is entirely separate from ASP.NET and is not, as such, an ASP.NET authentication mechanism.
Different Windows operating systems use different authorities to determine whether credentials are valid. In Microsoft Windows NT® version 4, user name and password information was stored in the Security Accounts Manager (SAM), and validation was performed by the NT LAN Manager (NTLM); however, since IIS 5.0 is required for ASP.NET and works only under Windows 2000 or later, you probably will not encounter these entities. In Windows 2000 or Windows XP, user name and password information is stored in the Microsoft Active Directory® database, and validation is performed by a protocol called Kerberos. Regardless of your operating system, most of the work of validating credentials is done behind the scenes, and configuring authentication is only a matter of adjusting some values in an IIS dialog window.
To configure Integrated Windows authentication, you will need to use the Internet Service Manager (the configuration client for IIS). In Windows 2000, this application can be found on the Start menu under Programs, Administrative Tools, Internet Services Manager. In Windows XP, you will need to open the Control Panel, select Administrative Tools, and then select Internet Information Services.
Find the virtual directory for the application to which you want to add authentication. Right-click the directory name, click Properties, and then click the Directory Security tab. Click the Edit button under Anonymous access and authentication control. This will open the Authentication Methods window in which you can configure the IIS authentication rules.
To turn on Windows Authentication, simply deselect the Anonymous access checkbox. This tells IIS that anonymous access is not allowed to this Web location, and therefore credentials are necessary.
Note that if you try opening the page whose authorization settings you just changed in a browser, it will probably let you access the page without having to enter a user name or password. This is because, presumably, you are already logged in to the same domain as the Web application, and therefore it already knows who you are. Users not logged in to the domain will have to log in at access time; they will have three chances, and IIS will return an Access Denied error page if all three fail.
One major caveat to this authentication scheme is that users must be able to log on to the domain on which the server is running. This means that Integrated Windows authentication is only suitable for intranet Web applications, as remote users cannot log on to your network. However, because this protocol does not send passwords over the network, it is extremely secure; therefore, if you are running intranet Web applications, this type of authentication is highly preferable to other less-secure modes such as ASP.NET basic or form-based authentication.

Basic Authentication

ASP.NET basic authentication is very similar to basic authentication under JSP. If a Web resource requires basic authentication, browsers pointed at that resource will open a browser-specific login dialog that requires the user to enter a name and password. Users of basic authentication do not require accounts on the server domain, as they did with Windows authentication. As with JSP basic (and form-based) authentication, however, passwords are sent in base64 encoding over HTTP and are not encrypted in any way.

Configuration

Like Integrated Windows authentication, basic authentication is performed by IIS and therefore needs to be configured in IIS. Open the Internet Services Manager and go to the Authentication Methods dialog for your virtual directory, as detailed in the previous section. You want to disable Anonymous access and Integrated Windows authentication, and enable basic authentication.
Note that we provide a default domain name and realm for our application. The domain name should match the domain name of your Web service (that is, the one that has permission to access the application). As in JSP, the realm name will simply be used to subtitle the Login dialog box when it appears. Also note that when you select basic authentication, IIS will warn you that your password will be sent unencrypted over the network and that this is a major security risk. As previously mentioned, basic authentication is completely insecure and requires an additional protocol such as SSL to make it safe.

User names and passwords

When using basic authentication, user names and passwords are stored as user accounts on the system on which the server is running. This means that you need to use the Windows utility for adding user accounts; only valid Windows accounts can be used to log in using basic authentication. The User Accounts setup and wizard can be found in the Windows Control Panel. Adding a new user to the system is relatively self-explanatory.

Security configuration in ASP.NET

You may recall that in JSP, login and security configuration is done in an XML document called Web.xml. Similarly, every ASP.NET application has an XML file called Web.config that is automatically generated for it upon creation. You can edit Web.config in any text editor such as Notepad, or you can open it in Microsoft Visual Studio® .NET by double-clicking it in the Solution Explorer at the right side of the screen.
Open Web.config, and scroll down until you see an element that looks something like this:
<authentication mode=Windows />
It is inside this element where all ASP.NET authentication settings should be placed. For basic authentication, however, you do not need to modify any settings in Web.config. Later, when we discuss form-based authentication, we will be making many changes to this configuration file. For now, simply note that the Windows mode indicates that IIS will handle the authentication process for this application; Windows mode is used for both basic authentication and Integrated Windows authentication.

Accessing the page

If you set up IIS according to the instructions above, you should now be able to open your application in a Web browser and see a login dialog.
Notice that this dialog is exactly the same as the one produced by our JSP basic authentication example. This is because the dialog box style is specific to the browser (in this case Internet Explorer) and not to the programming language used to develop the application or the server on which it runs.
Basic authentication under Windows, by default, will allow three attempts at a correct user name and password combination. If all three fail, it will send an HTTP 401.2 Unauthorized error. Since basic authentication is performed by IIS and not by ASP.NET, you cannot create customized error pages since ASP.NET will never have a chance to see the request.

Form-based Authentication

Form-based authentication is similar to basic authentication, except that it allows you to define your own login and error pages. In addition, it does not require the additional setup in IIS that basic authentication requires. Before starting the example in this section, you should go into IIS and change the authentication settings back to what they originally were (that is, allow anonymous access and Integrated Windows authentication, but not basic authentication).

Login configuration

In the section on basic authentication, we introduced the Web.config file. Recall that this file is generated for each Web application, and that it stores all of the configuration information about the application in XML format. In order to tell the application that we are using form-based authentication, we need to make some changes to the <authentication> element in Web.config.
Open your application project in Visual Studio .NET, double-click Web.config to open it, and scroll down to the <authentication> element. Modify it so that it looks like Listing 7.
Listing 7. <authentication> element for forms-based authentication
<authentication mode="Forms">
   <forms name="LoginForm" loginUrl="login.aspx" protection="All" />
</authentication>
The name and loginUrl attributes are self-explanatory. The protection element requires a little more explanation. When you use forms authentication, ASP.NET looks for a Forms cookie on the browser that is accessing the Web application. If it does not find one, it forwards the browser to the specified login page. If it does find one, it assumes the browser has already logged in during this session (that is, it already knows who the user is) and proceeds directly to the requested page. The protection element indicates to what degree this cookie will be encrypted and validated for security. All is the highest and most reliable setting; others are available, and more information on them can be found on MSDN®.
Since we are not going to be using IIS authorization to control access to anonymous users, we also need to add an additional element to Web.config. The <authorization> element, shown in Listing 8, allows you to permit or deny particular users or groups of users to use the application. In the case of Listing 8, we are denying access to all anonymous users (the special character ? represents anonymous users).
Listing 8. Denying anonymous users access
<authorization>
   <deny users=? />
</authorization>
We could also have added <deny> elements for specific user names, allowed access to some users and not others, and so on.
User names and passwords
For our purposes, the easiest way to store user names and passwords is in the Web.config XML file, right alongside the other authentication information. In reality, because user names and passwords are accessed programmatically in ASP.NET (as we will see shortly), you could easily retrieve them from a database or a customized XML file of your own design. In many cases such methods will be preferable (and possibly more similar to what you did with your JSP applications), so we will point out where and when such code should be added when we look at the ASP.NET code in just a moment.
For now, find the <authentication> element in Web.config again and add to it so that it looks like Listing 9.
Listing 9. Storing user name and password information in Web.config
<authentication mode="Forms">
   <forms name="LoginForm" loginUrl="login.aspx" protection="All" />
      <credentials passwordFormat="Clear">
         <user name="craig" password="secret"/>
      </credentials>
   </forms>
</authentication>
Using the <credentials> element, we have added one user to the list of potential users for this application. We will see in a moment how to check against the users in this list. For now, note the passwordFormat attribute; a value of Clear indicates that this password will be readable to humans (that is, unencoded). Additional values are available that will cause the password to be encrypted before being sent across the network.

Designing a login form

Unlike in our JSP example, we can take advantage of Visual Studio .NET and design the appearance of our ASP.NET login form using the forms designer, and place all important code in the CodeBehind file. This allows us to have a much better idea of what the form will look like while designing it, and also allows us to keep most of the C# code separate from the HTML page design.
We'll start by adding a new form to the project called Login.aspx. We can add some text fields and a button to this form to make it look similar to the form we created in our JSP example simply drag and drop the necessary components into the design window and arrange them.
Now, open the CodeBehind file for Login.aspx. Here we need to add code in two different places. First, we need to add the following using directive to the top of the page:
using System.Web.Security;
This namespace contains all the necessary classes for ASP.NET security.
We then need to add some code to verify the user name and password to the Click method corresponding to our login button. If your CodeBehind does not already contain a Button1_Click method, go back to the form editor and double-click the login button to create one. Inside Button1_Click, add code as shown in Listing 10.
Listing 10. Button1_Click code for forms-based authentication
private void Button1_Click(object sender, System.EventArgs e) {
   if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text)) {
      FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
   } else {
      Label1.Text = "Login failed. Please try again.";
   }
}
As you can see, this code uses two methods of the FormsAuthentication object, which resides in the System.Web.Security namespace.
The Authenticate() method receives two string parameters representing a user name and password and checks them against the list of valid credentials in Web.config. In this case, we are checking whether the values in our two fields match an existing set of credentials.
The RedirectFromLoginPage() method receives two parameters as well. The first is a user name, which is passed to the applications authorization policy. Basically, it will be used to determine what parts of the application this user has access to, and what parts are restricted. The second parameter is a boolean indicating whether or not the application should send the user a persistent cookie. Setting this to false forces the user to log in if he or she opens the same application in a new browser window; setting it to true allows them to continually use the page in multiple browser windows without having to log in each time.
Notice also that our authentication and resulting actions from valid and invalid credentials are completely programmatic in nature. This means that instead of checking against the Web.config file using the FormsAuthentication class, we could easily have matched the provided credentials against a user database or against a custom XML file. Storing user names and passwords is an easy way because it allows you to use built in forms authentication methods, but it is certainly not the only or best way.
In addition, we could easily have redirected the user to a custom error page if the credentials were invalid instead of simply changing a message on the same page, much as we did in the JSP examples earlier in this document.

Accessing the page

Having saved and compiled your project, you can now access it using a Web browser. Assuming our application is called HelloForms, we can test out the login page by pointing a browser at http://localhost/HelloForms/WebForm1.aspx. The browser will redirect to the login page.
Notice how similar this page looks to the login page for our forms-based JSP example. If you enter invalid credentials, the label at the top of the window will change to an error message. Valid credentials (for example, craig and secret) will allow you to continue on to WebForm1.aspx.

Passport Authentication

You can also use the Passport authentication system from within .NET. This system offers an independent authentication and authorization system as a single login. That is, you sign in to Passport once and allow passport to sign you in to any Web site or Web application that allows Passport authentication. For more information on Passport, and using Passport in ASP.NET applications, see the MSDN Library.

Thursday 2 May 2013

User Control: Event Handling using Delegates


UserControl Page :


public partial class ButtonCombo : System.Web.UI.UserControl
{
public delegate void OnButtonClick(string val);
public event OnButtonClick eventHandler;
protected void Page_Load(object sender, EventArgs e){
}

protected void Button1_Click(object sender, EventArgs e){


if (eventHandler != null)eventHandler(
"Add");
// var classname = eventHandler.Method.DeclaringType;Response.Write("Added");
// Response.Write("Added " + classname);//eventHandler = null;}
protected void Button2_Click(object sender, EventArgs e){

if (eventHandler != null)eventHandler(
"Update");Response.Write(
"updated");
//eventHandler = null;}
protected void Button3_Click(object sender, EventArgs e){

if (eventHandler != null)eventHandler(
"Delete");Response.Write(
"Deleted");
//eventHandler = null;}
}


In ASPX page, take two pages say, Default.aspx and Home.aspx :
Use this usercontrol in both the pages.
Default.aspx

.......
</head>
<
body><form id="form1" runat="server"><div>
<USC1:UserControl runat="server" ID="Direct" EnableTheming="True" />..........
..........
</div>
</form></
body></
html>

Code Behind :

public partial class _Default : System.Web.UI.Page {


protected void Page_Load(object sender, EventArgs e){

if(Page.IsPostBack)Direct.eventHandler +=
new ButtonCombo.OnButtonClick(Direct_eventHandler);
}


void Direct_eventHandler(string val){

//val = "Hello";//Label1.Text=val;Response.Write("Operation : " +val);

}
}


Similarly in HOME.ASPX, use this usercontrol and write the similar event:

Home.Aspx :

public partial class Home : System.Web.UI.Page{
protected void Page_Load(object sender, EventArgs e){

if (Page.IsPostBack)Usc1.eventHandler +=
new ButtonCombo.OnButtonClick(Direct_eventHandler);}

void Direct_eventHandler(string val){

//val = "Hello";//Label1.Text = val;Response.Write(val + "In new page");}

}

   The Output of the Default page:





The Output of the Home page:



Hence this way we can handle the events in different pages, using delegate events. If we have 10 pages using the same user control, we can write our own logic in the events for each page and call the events of the user control accordingly.






Thursday 28 March 2013

IEnumerable and IQueryable

IEnumerable is inherited by IQueryable, hence it has all the features of it and except this, it has its own features

IEnumerable<T> is great for working with sequences that are iterated in-memory, but IQueryable<T> allows for out-of memory things like a remote data source, such as a database or web service.
 
 
IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.

The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements (or even do other things) based on a query. In the case of the IQueryable, the LINQ query gets used by IQueryProvider which must be interpreted or compiled in order to get the result. I.e., the extension methods defined for IQueryable take Expression objects instead of Func objects (which is what IEnumerable uses), meaning the delegate it receives is an expression tree instead of a method to invoke.

for example:
IEnumerable ->

IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));

The above statement represents the below query:

SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0WHERE [t0].[EmpName] LIKE @p0

IQueryable->

IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list = list.Take<Employee>(10); 
The above statement represents the below query:

SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
WHERE [t0].[EmpName] LIKE @p0



    Wednesday 27 February 2013

    Immutable String

    All strings in .NET are immutable. You never can change a content of any string. All string operations create a brand-new string

    We know that strings are reference type in .net. Due to this fact, they are allocated on heap and when in the scope their pointer come on to the stack. When we try and assign a new value to a string variable, we can get the new value assigned to our variable, but in the background, a new memory location is allocated and its reference is copied to out string variable making us feel that the value of the original one is changed. This feature is referred as immutable. Thus all string in .net are immutable.
    Due to this behavior of string we should always use StringBuilder class present in System.IO.Text namespace. System.Text.StringBuilder.Append does this thing much more effectively, because already available data is never copied again, the instance of StringBuilder mutates instead.

     if you have any repeated operation to compose a string, always use StringBuilder. Basically, using more than one string "+" in one expression is not very effective; string.Format function is much better, faster and more readable.


    string myString = "Immutable";
    char charI = myString[0];
    //you can do it
    //myString[0] = ' '; myString[1] = ' '; no way; it is immutable
    //
    array of char can be considered as some kind of string; it is mutable:
    char[] myText = new char['M', 'u', 't', 'a', 'b', 'l', 'e', ' ', ];
    myText[7] = '!';
    //you can do it! The result will be "Mutable!"

    Difference Between 'Ref' and 'Out'

    The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. For example:

    OUT Example:

    class OutExample
    {
        static void Method(out int i)
        {
            i = 44;
        }
        static void Main()
        {
            int value;
    Method(out value);
            // value is now 44    }
    }

    REF Example:

    class RefExample
        {
            static void Method(ref int i)
            {
                // Rest the mouse pointer over i to verify that it is an int.            // The following statement would cause a compiler error if i            // were boxed as an object.            i = i + 44;
            }
            static void Main()
            {
                int val = 1;
                Method(ref val);
                Console.WriteLine(val);
                // Output: 45        }
        }


    Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

    The ref and out keywords are treated differently at run-time, but they are treated the same at compile time. Therefore methods cannot be overloaded if one method takes a ref argument and the other takes an out argument. These two methods, for example, are identical in terms of compilation, so this code will not compile.

    Sunday 17 February 2013

    Open XMl :Get the value from the excel depending on some row value

    Using Open Xml, I have extracted the data from the excel sheet depending on a value, wherever there exist the value "CLOSED" in the "Status" column, I need its whole row and display in the grid. For example lets my excel looks like this: 


    The column "Current Status" is in G column which contains some values, I need to extact the values from the excel where current status is closed and display. The code is as follows, where I have used open Xml :

    the page designed with one fileuploader, ane button and a gridview to display the result. the code goes like this:

    protected void Button1_Click(object sender, EventArgs e)
    {

    DataTable dt= ReadXml();GridView1.DataSource = dt;
    GridView1.DataBind();
    }


    private DataTable ReadXml(){

    string val = null;
    DataRow rw = null;
    int j = 0;
    DataTable dt = TableStruc();
    //get the path of the excel sheetusing (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(FileUpload1.PostedFile.FileName, false)){

    //open the sheetvar sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>().First();
    WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheets.Id);
    Worksheet worksheet = worksheetPart.Worksheet;
    //Get the first sheet of the excelSheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
    SharedStringTablePart stringTable = spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
    //get the total rows in the sheet to loop over the sheet to check the dataint rowCount = worksheet.Descendants<Cell>().Count<Cell>();
    uint rowind = 2;
    for (int i = 0; i < rowCount; i++){

    //get the value of cell G where the status of CMR is being written(Closed,Open,worked...)Cell cell = GetCell(worksheet, "G", rowind);
    if (cell != null){

    //Get the text value of that cell in a variableval = cell.CellValue.Text;
    //check the datatype of the value,if it is sting---if (val != null && cell.DataType.Value == CellValues.SharedString){

    var tableEntry = stringTable.SharedStringTable.ElementAt(int.Parse(val));
    if (tableEntry != null){
    val = tableEntry.InnerText;

    //Do Something if the status is CLosedif (val =="CLOSED"){

    //a new row is added to the datatable to add the values of rw = dt.NewRow();
    Row r= GetRow(worksheet, rowind);
    foreach (Cell c in r.Elements<Cell>()){
    val = c.CellValue.Text;

    if (c.DataType!=null){

    if(c.DataType.Value== CellValues.SharedString)tableEntry = stringTable.SharedStringTable.ElementAt(
    int.Parse(val));val = tableEntry.InnerText;
    }

    elseval = c.CellValue.Text;
    rw[j++]= val;
    }
    dt.Rows.Add(rw);
    j = 0;
    }

    }
    }
    rowind++;
    }
    }

    }
    return dt;}



    private static Cell GetCell(Worksheet worksheet,string columnName, uint rowIndex){

    Row row = GetRow(worksheet, rowIndex);
    if (row == null)
    return null;
    return row.Elements<Cell>().Where(c => string.Compare(c.CellReference.Value, columnName +
    rowIndex,
    true) == 0).First();}



    private static Row GetRow(Worksheet worksheet, uint rowIndex){

    try{
    return worksheet.GetFirstChild<SheetData>().Elements<
    Row>().Where(r => r.RowIndex == rowIndex).First();}

    catch (Exception){

    return null;}
    }


    private DataTable TableStruc(){

    DataTable dt = new DataTable();
    DataColumn dc1 = new DataColumn() { ColumnName = "requestno", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc1);

    DataColumn dc2 = new DataColumn() { ColumnName = "group", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc2);

    DataColumn dc3 = new DataColumn() { ColumnName = "changedate", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc3);

    //DataColumn dc4 = new DataColumn() { ColumnName = "changetime", DataType = System.Type.GetType("System.String") };//dt.Columns.Add(dc4);DataColumn dc8 = new DataColumn() { ColumnName = "changetype", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc8);

    DataColumn dc11 = new DataColumn() { ColumnName = "description", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc11);

    DataColumn dc9 = new DataColumn() { ColumnName = "requester", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc9);

    DataColumn dc10 = new DataColumn() { ColumnName = "status", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc10);

    DataColumn dc5 = new DataColumn() { ColumnName = "closuredate", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc5);

    //DataColumn dc6 = new DataColumn() { ColumnName = "closuretime", DataType = System.Type.GetType("System.String") };//dt.Columns.Add(dc6);DataColumn dc7 = new DataColumn() { ColumnName = "approval", DataType = System.Type.GetType("System.String") };dt.Columns.Add(dc7);

    return dt;}



    The above code when executed looks like :


    As seen above only those data are displayed where the current status is "Closed".

    Use of Generic Dictionary<>

    Dictionary contains a key and a value. Each key is correspond to one value. It is very useful, when u have some value according to another value, and u need to keep track of which one is correspond to which value.
    I had certain situations where Dictionary was valuable for me. here I would post one of those:

    Declare:

    public Dictionary<string, string> GridVal = new Dictionary<string, string>();


    Use To Filter Data :

    The Design is as follows:

    According to the selected item we need to filter the data and show it in the gridview. here I have used Dictionary to form the condition, to select the data from the database, according the the section user makes.

    Code:

    protected void btnFilter_Click(object sender, EventArgs e){

    try{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();GetSelectedValues();
    GetConditions();

    //ds= TMBL.GetGridValue(Convert.ToInt32(ddlGenerateYear.Text.Trim()));//ViewState["Dataset"] = ds;ds = (DataSet)ViewState["Dataset"];
    if (ds.Tables[0].Select(TMUtil.queryCondition).Any()){
    dt = ds.Tables[0].Select(TMUtil.queryCondition).CopyToDataTable();
    gvTMInitialForecast.DataSource = dt;
    gvTMInitialForecast.DataBind();
    }

    else{
    gvTMInitialForecast.DataBind();
    LblError.Visible =
    true;LblError.Text =
    "No Data Found As Per Your Search";}
    }

    catch{
    //gvTMInitialForecast.Visible = false;LblError.Visible = true;LblError.Text =
    "No Data Found As Per Your Search";}
    }



    private void GetConditions(){
    TMUtil.queryCondition =
    "";
    foreach( KeyValuePair<string, string> value in TMUtil.GridVal){

    if (TMUtil.queryCondition != "")TMUtil.queryCondition = TMUtil.queryCondition +
    " and ";TMUtil.queryCondition = TMUtil.queryCondition+value.Key +
    " = '"+ value.Value +"'";
    }
    }
    // Get the values selected by the user and store it in Dictionary<>


    private void GetSelectedValues(){
    if (ddlProjectLOB.Text != "")TMUtil.GridVal[
    "ProjectLOB"] = ddlProjectLOB.Text.Trim();//Gridval is the dictionary having "ProjectLOB" as key and the ddl text as its value
    if (ddlPortfolio.Text != "")TMUtil.GridVal[
    "Portfolio"] = ddlPortfolio.Text.Trim();
      if (ddlProjectID.Text != "")
    TMUtil.GridVal[
    "ProjectID"] = ddlProjectID.Text.Trim();
      if(ddlLocation.Text!="")
    TMUtil.GridVal[
    "Region"] = ddlLocation.Text.Trim();
      if (ddlRole.Text != "")
    TMUtil.GridVal[
    "[Role]"] = ddlRole.Text.Trim();
      if(ddlEmployeeID.Text!="")
    TMUtil.GridVal[
    "ResourceID"] = ddlEmployeeID.Text.Trim();
      if (ddlYear.Text != "")
    TMUtil.GridVal[
    "ForecastYear"] = ddlYear.Text.Trim();
      if(ddlMonth.Text!="")
    TMUtil.GridVal[
    "Month"] = ddlMonth.Text.Trim();
    }



    The Viewstate already contains the dataset having the total value from the database, and then the filter is done on this dataset,according to the condition. the condition is framed with the help of DICTIONARY<>. Dictionary contails the name of the column as its key and the value selected by the user as its value. now while framing the condition, we use the key and the value both. this condition is just use to filter data from the dataset.