Menu ▼

Home / blogs /

<< < 1 2 3 4 5 6 7 8 9 10 > >>

To take backup of dll in GAC follow the below setps.

  • Open Windows Run
  • Type C:\Windows\assembly\GAC_MSIL and click enter
  • All the GAC MSIL dll's will be opened
  • You can take backup of what ever dll you want

Read More...
Submited By : mrkraju On 14 Jul 2016

This example shows you how to bind data to DropDownList in GridView based on the Grid Row Value. In this example we will bind the States to DropDownList based on Country in Row.

In the GridView RowDataBound we will find the DropDownList and Country then fetch the state list for the Country and bind the state list to DropDownList.

RowDataBound event

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int CountryID = int.Parse(((HiddenField)e.Row.FindControl("hidCountryID")).Value);
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlState");
            ddl.DataSource = GetStates(CountryID);
            ddl.DataTextField = "State";
            ddl.DataValueField = "StateID";
            ddl.DataBind();
        }
    }

Example
Dropdown binding in GridView

CS Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Text;
using System.Collections;

namespace WebApp
{
    public partial class Sample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillGrid();
            }
        }

        void FillGrid()
        {
            gv.DataSource = GetCountries();
            gv.DataBind();
        }

        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int CountryID = int.Parse(((HiddenField)e.Row.FindControl("hidCountryID")).Value);
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddlState");
                ddl.DataSource = GetStates(CountryID);
                ddl.DataTextField = "State";
                ddl.DataValueField = "StateID";
                ddl.DataBind();
            }
        }

        DataTable GetCountries()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CountryID", typeof(int));
            dt.Columns.Add("Country", typeof(string));
            dt.Rows.Add(1, "Australia");
            dt.Rows.Add(2, "New Zealand");
            dt.Rows.Add(3, "India");
            dt.Rows.Add(4, "USA");
            return dt;
        }

        DataTable dtStates = null;

        DataTable GetStates(int CountryID)
        {
            if (dtStates == null)
            {
                dtStates = new DataTable();
                dtStates.Columns.Add("CountryID", typeof(int));
                dtStates.Columns.Add("StateID", typeof(string));
                dtStates.Columns.Add("State", typeof(string));
                dtStates.Rows.Add(1, 1, "Albury");
                dtStates.Rows.Add(1, 2, "Dubbo");
                dtStates.Rows.Add(1, 3, "Sydney");
                dtStates.Rows.Add(2, 1, "Auckland");
                dtStates.Rows.Add(2, 2, "Hamilton");
                dtStates.Rows.Add(2, 3, "Wellington");
                dtStates.Rows.Add(3, 1, "Delhi");
                dtStates.Rows.Add(3, 2, "Hyderabad");
                dtStates.Rows.Add(3, 3, "Mumbai");
                dtStates.Rows.Add(4, 1, "Chicago");
                dtStates.Rows.Add(4, 2, "New York");
                dtStates.Rows.Add(4, 3, "Washington DC");
            }
            dtStates.DefaultView.RowFilter ="CountryID=" + CountryID;
            return dtStates.DefaultView.ToTable();
        }


    }

}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs" Inherits="WebApp.Sample" %>

<!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="gv" runat="server" AutoGenerateColumns="False" 
            CellPadding="5" CellSpacing="5" ForeColor="#333333" GridLines="Both" 
            onrowdatabound="gv_RowDataBound"  >
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:HiddenField ID="hidCountryID" runat="server" Value='<%#Eval("CountryID") %>' />
                        <asp:Label ID="lblCountry" runat="server" Text='<%#Eval("Country") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="State">
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlState" runat="server" style="width:100%">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 20 Jun 2016

This example shows you how to write C# extension method and how to convert DataSet to JSON using JavaScriptSerializer.

By default DataSet doesnot have GetJSON method to get JOSN string from DataSet. So in this example I have written an extension method to add GetJSON method to DataSet and it will return JSON String as output.

    public static class DataSetExt
    {
        public static string GetJSON(this DataSet ds)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            ArrayList root = new ArrayList();
            List<Dictionary<string, object>> table;
            Dictionary<string, object> data;

            foreach (DataTable dt in ds.Tables)
            {
                table = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt.Rows)
                {
                    data = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        data.Add(col.ColumnName, dr[col]);
                    }
                    table.Add(data);
                }
                root.Add(table);
            }
            
            return serializer.Serialize(root);
        }
    }

Steps to write GetJSON extension method.

  • Class should be declared as static
  • Method name should be declared as static
  • Method parameter should be starts with "this" keyword and the Object(DataSet) and variable name(ds).
  • Using System.Web.Script.Serialization.JavaScriptSerializer we converted the DataSet to JSON using Dictionary and ArrayList.

Example
C# extension method

CS Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Text;
using System.Collections;

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

        protected void btnGetJSON_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("Employee Name", typeof(string));
            dt.Columns.Add("Salary", typeof(decimal));
            dt.Columns.Add("Department", typeof(string));
            dt.Rows.Add("John", 5000.00, "Marketing");
            dt.Rows.Add("Smith", 4000.00, "IT");
            dt.Rows.Add("Williams", 6000.00, "Sales");
            dt.Rows.Add("Vijay", 6500.00, "IT");
            ds.Tables.Add(dt);
            dt = new DataTable();
            dt.Columns.Add("StudentID", typeof(int));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Marks", typeof(int));
            dt.Columns.Add("Grade", typeof(string));
            dt.Rows.Add(1, "Suresh", 950, "A+");
            dt.Rows.Add(1, "Rama", 900, "A+");
            dt.Rows.Add(1, "Kishore", 750, "B");
            ds.Tables.Add(dt);
            divOutput.InnerHtml = ds.GetJSON();


        }

    }


    public static class DataSetExt
    {
        public static string GetJSON(this DataSet ds)
        {

            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            ArrayList root = new ArrayList();
            List<Dictionary<string, object>> table;
            Dictionary<string, object> data;

            foreach (DataTable dt in ds.Tables)
            {
                table = new List<Dictionary<string, object>>();
                foreach (DataRow dr in dt.Rows)
                {
                    data = new Dictionary<string, object>();
                    foreach (DataColumn col in dt.Columns)
                    {
                        data.Add(col.ColumnName, dr[col]);
                    }
                    table.Add(data);
                }
                root.Add(table);
            }
            
            return serializer.Serialize(root);
        }
    }
}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Sample.aspx.cs" Inherits="WebApp.Sample" %>

<!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">
    <asp:Button ID="btnGetJSON" runat="server" Text="Get JSON" OnClick="btnGetJSON_Click" />
    <br /><br />
    <div id="divOutput" runat="server">
        
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 17 Jun 2016

When you truncate the table data, table Identity will be reset automatically. But when you delete the records in the table Identity will not be reset.

Below query will reset the table Identity in SQL server.

DBCC CHECKIDENT ('[TableName]', RESEED, 0);
GO

Read More...
Submited By : mrkraju On 15 Jun 2016

Below are the differences between Truncate and Delete in MS-SQL.

Delete Truncate
Can apply WHERE condition to filter records that need to be deleted. Cannot apply WHERE condition.
Delete is DML command. Truncate is DDL command.
Works against table row (locks the table row). Works against table (locks the table).
By using transactions you can rollback the deleted records. You cannot roll back the deleted records.
Trigger will fire when Delete the rows. Truncate cannot activate Trigger (Trigger will no fire)
No impact on identity. Resets the Column identity.

Read More...
Submited By : mrkraju On 15 Jun 2016

This example shows you how to restore SQL database from a backup file using SQL Query.

Example
USE MASTER
GO


ALTER DATABASE SampleDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Go


RESTORE DATABASE SampleDB
FROM DISK = N'E:\DB\Bakup\SampleDBBackupfile.bak'
Go


ALTER DATABASE SampleDB
SET MULTI_USER with ROLLBACK IMMEDIATE
Go


In the above example
SampleDB is the database name.
N'E:\DB\Bakup\SampleDBBackupfile.bak' physical path of backup file.

Read More...
Submited By : mrkraju On 28 Apr 2016

This example shows you how to show/hide the jQuery UI tooltip based on the given value in a textbox. In this example we have taken a textbox for age and when the user enter the age not in the range of 1 to 100 then it should show the tooltip.

Example
Enter Age:

Code to show the tooltip
$("#txtage").tooltip({
    items: "#txtage",
    content: "Age should be between 1 and 100."
});
$("#txtage").tooltip("open");

Code to hide the tooltip
$("#txtage").tooltip("disable");

Source code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script language="javascript">
        $(document).ready(function () {
            var agetooltip = null;
            $("#txtage").on("keyup", function () {
                if ($("#txtage").val() == "") {
                    if (agetooltip != null)
                        $("#txtage").tooltip("disable");
                }
                else {
                    var age = parseInt($("#txtage").val(), 10);
                    if (age >= 1 && age <= 100) {
                        if (agetooltip != null)
                            $("#txtage").tooltip("disable");
                    }
                    else {
                        if (agetooltip == null)
                            agetooltip = $("#txtage").tooltip({
                                items: "#txtage",
                                content: "Age should be between 1 and 100."
                            });
                        $("#txtage").tooltip("open");
                    }
                }
            });
        });
    </script>
</head>
<body>
    Enter Age:
    <input type="text" id="txtage" />
</body>
</html>
Read More...
Submited By : mrkraju On 13 Apr 2016

Sometimes when you done changes in table columns and save, you will get the below error

Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

To resolve this issue simple do the below two setps.

  • Goto "Tools" -> Open "Options"
    SQL Tools Options
  • Select "Designers" -> "Table and Database Designers" and Uncheck the checkbox "Prevent saving changes that require table re-creation" and click "OK"
    Prevent saving changes that require table re-creation

Read More...
Submited By : mrkraju On 12 Feb 2016

This example shows you how to export datatable or dataset data to excel in asp.net and c#. By using EPPlus.dll we can easily export datatable or dataset data to excel. You can merge cells, give background color and can format the cell text in excel using EPPlus.dll in c# and asp.net

In the below example we have a dataset contains student details and product details. By using EPPlus.dll we will export the data to excel. Datatable1 (students) data will be exported to students sheet and Datatable2 (products) data will be exported to products sheet in the same excel. And we can dynamically merge the heading of the sheet and can give the border for dynamic data.

Example
Export Datatable or Dataset data to excel

C# code

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 OfficeOpenXml;

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

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        CreateExcelFile();
    }

    DataSet GetData()
    {
        DataTable dt = new DataTable("Students");
        dt.Columns.Add("StudentID", typeof(int));
        dt.Columns.Add("StudentName", typeof(string));
        dt.Columns.Add("RollNumber", typeof(int));
        dt.Columns.Add("TotalMarks", typeof(int));
        dt.Rows.Add(1, "Jame's", 101, 900);
        dt.Rows.Add(2, "Steave, Smith", 105, 820);
        dt.Rows.Add(3, "Mark\"Waugh", 109, 850);
        dt.Rows.Add(4, "Steave,\"Waugh", 110, 950);
        dt.Rows.Add(5, "Smith", 111, 910);
        dt.Rows.Add(6, "Williams", 115, 864);
        DataSet ds = new DataSet("Example-DotnetLearners");
        ds.Tables.Add(dt);

        dt = new DataTable("Prodcuts");
        dt.Columns.Add("ProductID", typeof(int));
        dt.Columns.Add("ProductName", typeof(string));
        dt.Columns.Add("UnitPrice", typeof(decimal));
        for (int i = 1; i <= 100; i++)
            dt.Rows.Add(i, "Product - " + i.ToString(), i * 1.123);
        ds.Tables.Add(dt);
        return ds;
    }

    void CreateExcelFile()
    {
        try
        {
            using (DataSet ds = GetData())
            {
                if (ds != null && ds.Tables.Count > 0)
                {
                    using (ExcelPackage xp = new ExcelPackage())
                    {
                        foreach (DataTable dt in ds.Tables)
                        {
                            ExcelWorksheet ws = xp.Workbook.Worksheets.Add(dt.TableName);

                            int rowstart = 2;
                            int colstart = 2;
                            int rowend = rowstart;
                            int colend = colstart + dt.Columns.Count;

                            ws.Cells[rowstart, colstart, rowend, colend].Merge = true;
                            ws.Cells[rowstart, colstart, rowend, colend].Value = dt.TableName;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Font.Bold = true;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                            ws.Cells[rowstart, colstart, rowend, colend].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);

                            rowstart += 2;
                            rowend = rowstart + dt.Rows.Count;
                            ws.Cells[rowstart, colstart].LoadFromDataTable(dt, true);
                            int i = 1;
                            foreach (DataColumn dc in dt.Columns)
                            {
                                i++;
                                if (dc.DataType == typeof(decimal))
                                    ws.Column(i).Style.Numberformat.Format = "#0.00";
                            }
                            ws.Cells[ws.Dimension.Address].AutoFitColumns();



                            ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Top.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Bottom.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Left.Style =
                               ws.Cells[rowstart, colstart, rowend, colend].Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;

                        }
                        Response.AddHeader("content-disposition", "attachment;filename=" + ds.DataSetName + ".xlsx");
                        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        Response.BinaryWrite(xp.GetAsByteArray());
                        Response.End();
                    }
                }
            }
        }
        catch
        {
            throw;
        }
    }
}

ASPX Page

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

<!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:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />
    </div>
    </form>
</body>
</html>

Read More...
Submited By : mrkraju On 17 Dec 2015

This example shows you how to insert data from dataset or datatble to sql table using sql bulk copy in c#.

Dataset
sql bulk copy dataset

C# Code

protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = GetData();
    SqlConnection con = new SqlConnection(@"data source=.\sqlserver; user id=sa; password=123; database=Sample;");
    SqlBulkCopy bulk = new SqlBulkCopy(con);
    bulk.DestinationTableName = "tblStudents";
    foreach (DataColumn col in ds.Tables[0].Columns)
        bulk.ColumnMappings.Add(col.ColumnName, col.ColumnName);
    con.Open();
    bulk.WriteToServer(ds.Tables[0]);
    con.Close();
}

DataSet GetData()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("StudentID", typeof(int));
    dt.Columns.Add("StudentName", typeof(string));
    dt.Columns.Add("RollNumber", typeof(int));
    dt.Columns.Add("TotalMarks", typeof(int));
    dt.Rows.Add(1, "Jame's", 101, 900);
    dt.Rows.Add(2, "Steave Smith", 105, 820);
    dt.Rows.Add(3, "Mark Waugh", 109, 850);
    dt.Rows.Add(4, "Steave Waugh", 110, 950);
    dt.Rows.Add(5, "Smith", 111, 910);
    dt.Rows.Add(6, "Williams", 115, 864);
    DataSet ds = new DataSet();
    ds.Tables.Add(dt);
    return ds;
}

SQL table before data inserted
SQL table before data inserted

SQL table after C# datatable/dataset data inserted using sql bulk copy
SQL table after C# datatable/dataset data inserted using sql bulk copy

Read More...
Submited By : mrkraju On 16 Dec 2015
<< < 1 2 3 4 5 6 7 8 9 10 > >>




Search dotnetlearners.com