Pages

Showing posts with label Data Table. Show all posts
Showing posts with label Data Table. Show all posts

Monday, August 19, 2013

Create Datatable manually-ASP.Net

Add Red Code to Create DataTable, change the columns name and Datatype according to your needs.

  // Initialise Datatable

        DataTable dt = new DataTable( );      

// add columns with their Datatypes

        dt.Columns.Add("Id", Type.GetType("System.Decimal"));                    // decimal type
        dt.Columns.Add("Country_ID", Type.GetType("System.String"));          // string type
        dt.Columns.Add("Name", Type.GetType("System.String"));
        dt.Columns.Add("Description", Type.GetType("System.String"));
        dt.Columns.Add("Url", Type.GetType("System.String"));
        dt.Columns.Add("Unique Url Name", Type.GetType("System.String"));
        dt.Columns.Add("Meta Title", Type.GetType("System.String"));
        dt.Columns.Add("Meta Keyword", Type.GetType("System.String"));
        dt.Columns.Add("Meta Description", Type.GetType("System.String"));



Details:

The below line is used to add a column with the Datatype:
dt.Columns.Add("Column_name", Type.GetType("System.DataType_name"));

Tuesday, July 30, 2013

Convert .txt file to Datatable- C#

 private DataTable TextToDataTable(string File, string TableName, string delimiter)
    {

        /// <summary>
        /// Converts a given delimited file into a dataset.
        /// Assumes that the first line  
        /// of the text file contains the column names.
        /// </summary>
        /// <param name="File">The name of the file to open</param>  
        /// <param name="TableName">The name of the
        /// Table to be made within the DataSet returned</param>
        /// <param name="delimiter">The string to delimit by</param>
        /// <returns></returns>

        //The DataSet to Return
        DataSet result = new DataSet();

        //Open the file in a stream reader.
        StreamReader s = new StreamReader(File);

        //Split the first line into the columns     
        string[] columns = s.ReadLine().Split(delimiter.ToCharArray());

        //Add the new DataTable to the RecordSet
        result.Tables.Add(TableName);

        //Cycle the colums, adding those that don't exist yet
        //and sequencing the one that do.
        foreach (string col in columns)
        {
            bool added = false;
            string next = "";
            int i = 0;
            while (!added)
            {
                //Build the column name and remove any unwanted characters.
                string columnname = col + next;
                columnname = columnname.Replace("#", "");
                columnname = columnname.Replace("'", "");
                columnname = columnname.Replace("&", "");

                //See if the column already exists
                if (!result.Tables[TableName].Columns.Contains(columnname))
                {
                    //if it doesn't then we add it here and mark it as added
                    result.Tables[TableName].Columns.Add(columnname);
                    added = true;
                }
                else
                {
                    //if it did exist then we increment the sequencer and try again.
                    i++;
                    next = "_" + i.ToString();
                }
            }
        }

        //Read the rest of the data in the file.      
        string AllData = s.ReadToEnd();
        //Split off each row at the Carriage Return/Line Feed
        //Default line ending in most windows exports.
        //You may have to edit this to match your particular file.
        //This will work for Excel, Access, etc. default exports.

        // string[] rows = AllData.Split("\r\n".ToCharArray());
        string[] rows = AllData.Split("\r\n".ToCharArray());

        //Now add each row to the DataSet      
        foreach (string r in rows)
        {
            if (r != "")
            {
                //Split the row at the delimiter.
                string[] items = r.Split(delimiter.ToCharArray());

                //Add the item
                result.Tables[TableName].Rows.Add(items);
            }
        }

        System.Data.DataTable dt = (System.Data.DataTable)result.Tables[0];

        //Return the imported data.      
        return dt;
    }

call it:

 DataTable dt = TextToDataTable(MapPath("org.txt"), "a", "|");  // (.txt file,Datatable name,delimiter)
 


Thursday, July 11, 2013

Remove the Duplicate Rows from Data Table using LINQ - C#

"dt" is the datatable with the duplicate rows , now we have to remove the duplicate rows 

the field on behalf on which we are removing the duplicate rows is the "Name" field.

var s = dt.AsEnumerable().GroupBy(t => t[0]).Where(t1 => t1.Count() > 1).ToList();


// make new datatable same as the dt, which will contains the unique rows

         DataTable dt_new = dt.Clone();   

// get rows from var "s" and insert into the new datatable "dt_new"

        foreach (var item in s)
        {
            DataRow dr =
dt_new.NewRow();
            dr["Name"] = item.Key.ToString();
           
dt_new.Rows.Add(dr);
        }


"dt_new" is the datatable contains all unique rows acc. to the Name

Filter DataTable using LINQ - C#


Here we have a DataTable "dt" with the various fileds with Duplicate data.

For Example we have records for population Country wise in the dt.

If, we have to show data acc. to "INDIA"

 DataTable dt_filtered = dt.AsEnumerable()  .Where(a => Convert.ToString(a["Country"]) = = "INDIA") .CopyToDataTable();

 Here "Country" is the field in the datatable by with we are filtering

"dt_filtered" contains data INDIA wise.

--------------------
If, we have to show data acc. to "US", Then 

DataTable dt_filtered = dt.AsEnumerable()  .Where(a => Convert.ToString(a["Country"]) = = "US") .CopyToDataTable();

"dt_filtered" contains data US wise.

Remove the Duplicate Rows from Data Table on the Behalf of Particular Column.

In this Example, I am Removing the Duplicate Rows From DataTable "dt" according to the Field "Country"

Lets have a look.........


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView2.aspx.cs"
    Inherits="GridViewSorting2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GrdDetails" runat="server" CellPadding="4" ForeColor="#333333"
            GridLines="None" AutoGenerateColumns="false" >
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="lbl_country" runat="server" Text='<%#Eval("Country") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>
        <br />
        <br />
        <asp:Button ID="btn_RemoveDuplicateResults" runat="server" Text="Remove Duplicate Results"
            OnClick="btn_RemoveDuplicateResults_Click" />
    </div>
    </form>
</body>
</html>
=====================================



=========================


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

public partial class GridView2 : System.Web.UI.Page
{
 
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {

        DataColumn col;
        DataRow row1;

        col = new DataColumn();
        col.ColumnName = "Country";
        col.DataType = System.Type.GetType("System.String");
        dt.Columns.Add(col);

        for (int i = 0; i < 2; i++)
        {
            row1 = dt.NewRow();
            row1["Country"] = "Delhi";
            dt.Rows.Add(row1);
        }
        for (int i = 0; i < 1; i++)
        {
            row1 = dt.NewRow();
            row1["Country"] = "Mumbai";
            dt.Rows.Add(row1);
        }
        for (int i = 0; i < 5; i++)
        {
            row1 = dt.NewRow();
            row1["Country"] = "kolkata";
            dt.Rows.Add(row1);
        }
        BindGridview();
    }

    public void BindGridview()
    {
        GrdDetails.DataSource = dt;
        GrdDetails.DataBind();
    }
 
  
    protected void btn_RemoveDuplicateResults_Click(object sender, EventArgs e)
    {
        Hashtable hTable = new Hashtable();
        ArrayList duplicateList = new ArrayList();

        //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
        //And add duplicate item value in arraylist.
        foreach (DataRow drow in dt.Rows)
        {
            if (hTable.Contains(drow["Country"]))
                duplicateList.Add(drow);
            else
                hTable.Add(drow["Country"], string.Empty);
        }

        //Removing a list of duplicate items from datatable.
        foreach (DataRow dRow in duplicateList)
            dt.Rows.Remove(dRow);

        //Datatable which contains unique records will be return as output.
        DataTable dt22 = dt.Copy();

        BindGridview()
    }
}