Saturday 27 October 2012

bind dropdownlist in gridview in asp.net


In this article I will explain how to bind data to dropdownlist in inside of gridview in asp.net.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>bind dropdownlist in gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="Gv_Data" runat="server" AutoGenerateColumns="false"OnRowDataBound="Gv_Data_RowDataBound" >
<Columns>
<asp:BoundField DataField="ProductId" HeaderText="ProductId" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" />
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:DropDownList ID="ddllist" runat="server" Width="100px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

Now add following namespaces in codebehind:



SqlConnection con =new SqlConnection(" Your connection string");


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Products", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
Datatable dt=New Datatable();
da.Fill(dt);
con.Close();
Gv_Data.DataSource = dt;
Gv_Data.DataBind();

}

protected void Gv_Data_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
var ddl = (DropDownList)e.Row.FindControl("ddllist");
int ProductId = Convert.ToInt32(e.Row.Cells[0].Text);
SqlCommand cmd = new SqlCommand("select * from Products where ProductID=" + ProductId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
Datatable dt=New datatable();
da.Fill(dt);
con.Close();
ddl.DataSource = dt;
ddl.DataTextField = "ProductName";
ddl.DataValueField = "ProductID";
ddl.DataBind();
ddl.Items.Insert(0,"Select");
}
}

Friday 26 October 2012

How to create loginpage in asp.net using linq

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!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 id="Head1" runat="server">
    <title>LoginPage</title>

     <script type="text/javascript">
         function form_validate() {
             if (document.getElementById("<%=Txt_userid.ClientID%>").value == "") {
                 alert("Please enter UserId");
                 document.getElementById("<%=Txt_userid.ClientID%>").focus();
                 return false;
             }
             if (document.getElementById("<%=Txt_password.ClientID %>").value == "") {
                 alert("please enter password");
                 document.getElementById("<%=Txt_password.ClientID %>").focus();
                 return false;
             }
         }
  </script>
 </head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>       
      User Id<asp:TextBox ID="Txt_userid" runat="server"
                             MaxLength="15" CssClass="Txtbox"> </asp:TextBox>
        Password <td><asp:TextBox ID="Txt_password" runat="server"
                            TextMode="Password"    MaxLength="15" CssClass="Txtbox" ></asp:TextBox>

       <asp:Button ID="Btn_Submit"  runat="server"  Text="Login"
                             onclick="Btn_Submit_Click"  OnClientClick="return form_validate()" />         
 
    </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.SqlClient;
using System.Data;

public partial class Login : System.Web.UI.Page
{
    DataClassesDataContext db = new DataClassesDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Txt_userid.Text = "";

            Txt_userid.Focus();
        }
    }
    protected void Btn_Submit_Click(object sender, EventArgs e)
    {
        try
        {
            var count = (from myuser in db.Users
                         from mypass in db.Passwords
                         where (myuser.Id == Convert.ToInt32(Txt_userid.Text) && myuser.Password == Txt_password.Text)
                         || (mypass.UId == Convert.ToInt32(Txt_userid.Text) && mypass.Pass == Txt_password.Text)
                         select myuser.Id).Count();

            if (count > 0)
            {
                Session["UserId"] = Txt_userid.Text;

                IQueryable<int> que = from r in db.RolePages
                                      join u in db.Users on r.RoleId equals u.Role_Id
                                      where r.RoleId == u.Role_Id && u.Id == Convert.ToInt32(Txt_userid.Text)
                                      select r.RoleId;

                foreach (int i in que)
                {
                    Session["rolid"] = i;
                }

                form_load();
            }
            else
            {            
                ScriptManager.RegisterStartupScript(this, GetType(), "msg", "<script>alert('Invalid Login');</script>", false);

                Txt_password.Focus();
            }
        }
        catch
        {
            throw;
        }
    }
    private void form_load()
    {
        if(Session["rolid"].ToString()=="2")    
            {          
                Response.Redirect("Vulnerabilities.aspx", false);
            }
            else
            {
                Response.Redirect("SearchPage.aspx", false);
            }
        }
    }

Client Side Validation using JavaScript

Introduction

In this article how we can validate TextBox and DropDownList using JavaScript.


OnClientClick="return validate();" is used to call the JavaScript function on click of the Submit button.
Now we will add JavaScript code to implement client side implementation.
Firstly we will add a JavaScript function:

<script type="text/javascript">
function form_validate()
{
//Java script
}
 </script>

When user enters wrong information or may the user leaves a textbox blank, then the client side validation will be work. This will reduce server traffic.
 the complete JavaScript function:


<script type="text/javascript">

         function form_validate() {
             if (document.getElementById("<%=Txt_userid.ClientID%>").value == "") {
                 alert("Please enter UserId");
                 document.getElementById("<%=Txt_userid.ClientID%>").focus();
                 return false;
             }
             if (document.getElementById("<%=Txt_password.ClientID %>").value == "") {
                 alert("please enter password");
                 document.getElementById("<%=Txt_password.ClientID %>").focus();
                 return false;
             }
               if (document.getElementById("<%=ddllist.ClientID %>").value =='Select') {
                 alert("please enter password");
                 document.getElementById("<%=ddllist.ClientID %>").focus();
                 return false;
             }
         }
  </script>

 </head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>

 <asp:TextBox ID="Txt_userid "  runat="server"></asp:TextBox>

<asp:TextBox ID="Txt_password "  runat="server"></asp:TextBox>

<asp:DropDownList  ID="ddllist" runat="server"></asp:DropDownList>

  <asp:Button ID="Btn_Submit"  runat="server"
             Text="Submit" onclick="Btn_Submit_Click" OnClientClick="return form_validate()" />     
    </form>
</body>
</html>


Insert Excel file data into database in asp.net


Introduction

Here I will explain how to Import or insert data into SQL database from Excel spreadsheet using Sqlbulkcopy method.

Description

 I have searched for so many posts that explain static manner some of the posts are not clearly some of the posts are not supporting for latest excel files so many problems i faced by using those examples I have done application that will support for all excel versions and it will work for you without having any problems and it will dynamically you can upload excel sheet from anywhere from your computer.

I want to copy this exeltable data into a SQL Server Database Table, called Excel_table, with the same schema.


Design your aspx page like this

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

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <table class="style1">
            <tr>
                <td>
                    Table Name</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    Excel File Upload</td>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
 
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    </form>
</body>
</html>

After that write the following code in codebehind button click 

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.Data.SqlClient;
using System.IO;
using System.Data.OleDb;

public partial class ExcelExample2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(@"Data                                      Source=.\SQLEXPRESS;AttachDbFilename=D:\WebSite1
                        \WebSite1\App_Data\EmployeeDatabase.mdf;Integrated
                                                 Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {
       // form_lolll();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlDataAdapter da = new SqlDataAdapter(@"SELECT TABLE_NAME
                                                           FROM INFORMATION_SCHEMA.TABLES ", con);

            DataTable dt = new DataTable();

            da.Fill(dt);

            bool flag;

            if (dt.Rows.Count > 0)
            {
                string tableName_Txt = TextBox1.Text;

                flag = false;

                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    string tablename_DB = dt.Rows[j]["TABLE_NAME"].ToString();
                 
                    //compare database table and excel table
                    if (tableName_Txt == tablename_DB)
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    string connectionString = "";

                    if (FileUpload1.HasFile)
                    {
                        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

                        string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);

                        string fileLocation = Server.MapPath("~/App_Data/" + fileName);

                        FileUpload1.SaveAs(fileLocation);

                        //Check whether file extension is xls or xslx

                        if (fileExtension == ".xls")
                        {

                            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;
                                        Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;
                                        HDR=Yes;IMEX=2\"";
                        }
                        else if (fileExtension == ".xlsx")
                        {
                            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0
                              ;Data Source=" + fileLocation + ";Extended Properties=\"Excel ;
                              HDR=Yes;IMEX=2\"";
                        }

                        //Create OleDB Connection and OleDb Command

                        OleDbConnection conn = new OleDbConnection(connectionString);

                        OleDbCommand cmd = new OleDbCommand();

                        cmd.CommandType = System.Data.CommandType.Text;

                        cmd.Connection = conn;

                        OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);

                        DataTable dt1 = new DataTable();

                        conn.Open();

                        DataTable dtExcelSheetName = conn.GetOleDbSchemaTable
                                                                                            (OleDbSchemaGuid.Tables, null);

                        string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();

                        cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";

                        dAdapter.SelectCommand = cmd;

                        dAdapter.Fill(dt1);

                        conn.Close();


                        SqlDataAdapter da1 = new SqlDataAdapter(@"SELECT  *  FROM  "
                                                                                                      + tableName_Txt + "  ", con);
                        DataTable dt2 = new DataTable();

                        da1.Fill(dt2);
                       
                        //compare database table colums count and excel file colums count
                        if (dt1.Columns.Count == dt2.Columns.Count)
                        {
                            flag = false;

                            for (int i = 0; i < dt1.Columns.Count; i++)
                            {
                                  //compare database table colums names and excel file colum names

                                if (dt1.Columns[i].ColumnName == dt2.Columns[i].ColumnName
                                                          &    dt1.Columns[i].GetType() == dt2.Columns[i].GetType())
                                {
                                    flag = true;
                                }
                                else
                                {
                                    flag = false;
                                    Response.Write("Both Column Names are Not Equal \n");
                                    break;
                                }
                            }
                            if (flag)
                            {
                                con.Open();

                                conn.Open();

                                string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;
                                           Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;
                                                HDR=Yes;IMEX=2\"";

                                OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

                                excelConnection.Open();

                                OleDbCommand cmd1 = new OleDbCommand("Select *  from
                                                                                [" + getExcelSheetName + "]", excelConnection);

                                OleDbDataReader dr;

                                dr = cmd.ExecuteReader();

                                SqlBulkCopy sqlBulk = new SqlBulkCopy(con);

                                sqlBulk.DestinationTableName = tableName_Txt;

                                sqlBulk.WriteToServer(dr);

                                 excelConnection.Close();

                                 conn.Close();

                                 con.Close();

                                Label1.Text = "Insert successfully";

                            }
                        }
                        else
                        {
                            Label1.Text = "  Both Datatables Columns are Not Equal";
                        }
                    }
                }
                else
                {
                    Label1.Text = "Required Table Not Exits in DataBase";

                    TextBox1.Text = "";

                    TextBox1.Focus();
                }
            }
        }
        catch
        {
            throw;
        }
    }
}

create Xml file and bind to gridview in asp.net


XML file:

<?xml version="1.0" encoding="utf-8"?>
<EmpXml>
  <Emp1>
    <Name>Name1</Name>
    <Loc>Hyd</Loc>
    <Phone>12345434</Phone>
  </Emp1>
  <Emp1>
    <Name>krishna</Name>
    <Loc>Delhi</Loc>
    <Phone>90876</Phone>
  </Emp1>
  <Emp1>
    <Name>samba</Name>
    <Loc>karala</Loc>
    <Phone>898767665</Phone>
  </Emp1>
  <Emp1>
    <Name>nagapur</Name>
    <Loc>Hyd</Loc>
    <Phone>9998765</Phone>
  </Emp1>
  <Emp1>
    <Name>kumar</Name>
    <Loc>bang</Loc>
    <Phone>999999</Phone>
  </Emp1>
  <Emp1>
    <Name>naga</Name>
    <Loc>masurai</Loc>
    <Phone>87654</Phone>
  </Emp1>
  <Emp1>
    <Name>raghu</Name>
    <Loc>mumbai</Loc>
    <Phone>765433333</Phone>
  </Emp1>
</EmpXml>

sourcecode:

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

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
    </div>
    <table class="style1">
        <tr>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                EmpName</td>
            <td>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                EmpLoc</td>
            <td>
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                EmpPhone</td>
            <td>
                <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
            <td>
                <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
            </td>
        </tr>
    </table>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"      
        style="height: 133px; width: 281px">
    <Columns>
    <asp:BoundField  HeaderText="Name" DataField="Name" />
    <asp:BoundField HeaderText="Loc" DataField="Loc" />
    <asp:BoundField HeaderText="Phone" DataField="Phone" />
    <asp:CommandField ShowCancelButton="true" ShowDeleteButton="true" ShowEditButton="true" CancelText="Cancel" EditText="Edit" DeleteText="Delete" UpdateText="Update"/>
    </Columns>
     </asp:GridView>
    </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.SqlClient;
using System.Data;
using System.Xml;


public partial class LoadXmldata : System.Web.UI.Page

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind_data();
        }
    }
    private void bind_data()
    {
        DataSet ds = new DataSet();

        string filePath = Server.MapPath("EmpXml.xml");

        ds.ReadXml(filePath);

        GridView1.DataSource = ds.Tables[0].DefaultView;

        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        XmlDocument xmldoc = new XmlDocument();

        XmlElement parentelement=xmldoc.CreateElement("Emp1");

        xmldoc.Load(Server.MapPath("EmpXml.xml"));

        XmlElement name=xmldoc.CreateElement("Name");

        name.InnerText=TextBox1.Text;

        XmlElement loc=xmldoc.CreateElement("Loc");

        loc.InnerText=TextBox2.Text;

        XmlElement phone=xmldoc.CreateElement("Phone");

        phone.InnerText=TextBox3.Text;

        parentelement.AppendChild(name);

        parentelement.AppendChild(loc);

        parentelement.AppendChild(phone);

        xmldoc.DocumentElement.AppendChild(parentelement);

        xmldoc.Save(Server.MapPath("EmpXml.xml"));

        bind_data();
    }
}