Programming in almost language

This is the site where you may share your knowledge and experience to eachother..

  • Categories

  • LinkedIn

  • Tweet Me

  • My footsteps

Dynamic GridView(Edit,Delete,Insert,Select) Just copy paste and enjoy it

Posted by Praveen Kumar on May 9, 2008

Design(View Part)

<%@ Page Language=”C#” Title=”Untitled Page” CodeFile=”~/createaccount.aspx.cs” Inherits=”createaccount” %>
<script type=”text/javascript”>
function comparetext()
{    if((document.getElementById(txt_newpwd).contains)==(document.getElementById(txt_cnfpwd).contains))
alert(“hi”);
else
alert(“sorry”);
}</script>
<div id=”container”>
<div class=”header”>
<div class=”logo”>
<h1>Create Account</h1>
</div>
</div>
</div>
<div>

<asp:Panel ID=”p_Panel1″ runat=”server” Height=”590px” Style=”left: 0px; position: relative;
top: 0px;” Width=”674px” BorderColor=”Silver” BorderStyle=”Solid” BorderWidth=”1px”>
<div Style=”left: 0px; position: absolute; top: 0px; width: 336px; height: 582px;”>

<asp:GridView ID=”GridView_account” runat=”server” AutoGenerateColumns=”false” ShowFooter=”True”
OnRowCancelingEdit=”GridView_account_RowCancelingEdit” OnRowEditing=”GridView_account_RowEditing”
OnRowUpdating=”GridView_account_RowUpdating” OnRowCommand=”GridView_account_RowCommand”
OnRowDeleting=”GridView_account_RowDeleting” OnSelectedIndexChanged=”GridView_account_SelectedIndexChanged” DataKeyNames=”CID” Height=”110px” Width=”497px” >
<Columns>
<asp:TemplateField HeaderText=”ID” SortExpression=”departmentid”>
<ItemTemplate>
<asp:Label ID=”label_accid” runat=”server” Text='<%# Bind(“CID”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”User Name (required)” SortExpression=”CID”>
<EditItemTemplate>
<asp:TextBox ID=”txt_name” runat=”server” Text='<%# Bind(“NAME”) %>’></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txt_newname” runat=”server” ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID=”label_name” runat=”server” Text='<%# Bind(“NAME”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Password (required)”>
<EditItemTemplate>
<asp:TextBox ID=”txt_password” runat=”server” Text='<%# Bind(“PASSWORD”) %>’ TextMode=”Password”></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txt_newpassword” runat=”server” ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID=”label_pwd” runat=”server” Text=”*****”></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Email Address (required)” SortExpression=”CID”>
<EditItemTemplate>
<asp:TextBox ID=”txt_email” runat=”server” Text='<%# Bind(“EMAIL”) %>’></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txt_newemail” runat=”server” ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID=”label_email” runat=”server” Text='<%# Bind(“EMAIL”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Options” ShowHeader=”False”>
<EditItemTemplate>
<asp:LinkButton ID=”LinkButton_update” runat=”server” CausesValidation=”True” CommandName=”Update” Text=”Update”></asp:LinkButton>
<asp:LinkButton ID=”LinkButton_cancel” runat=”server” CausesValidation=”False” CommandName=”Cancel” Text=”Cancel”></asp:LinkButton>
<asp:LinkButton ID=”LinkButton_delete” runat=”server” CausesValidation=”False” CommandName=”Delete” Text=”Delete”></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID=”LinkButton_addnew” runat=”server” CausesValidation=”False” CommandName=”AddNew” Text=”Add New”></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID=”LinkButton_edit” runat=”server” CausesValidation=”False” CommandName=”Edit” Text=”Edit”></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Manage Role” ShowHeader=”False”>
<ItemTemplate>
<asp:LinkButton ID=”Selectbtn” runat=”server” CausesValidation=”False” CommandName=”Select” Text=”Select”></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”Button” />
<div Style=”left: 263px; position: absolute; top: -30px; width: 185px; height: 20px;” >
<asp:RadioButton ID=”adminradio” runat=”server” GroupName=”usertype” Text=”Admin”/>
<asp:RadioButton ID=”empradio” runat=”server” GroupName=”usertype” Text=”Employee” />
<asp:RadioButton ID=”genradio” runat=”server” GroupName=”usertype” Text=”General” Width=”54px” Checked=”True” />
</div>
</div>
</asp:Panel>
</div>

Code Behind

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Odbc;
using System.Security.Cryptography;
using System.Text;

public partial class createaccount : System.Web.UI.Page
{
OdbcConnection con;
OdbcCommand cmd;
OdbcDataReader myreader;
ConnectionClass objCon;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillgridview();
}
}//

private void fillgridview()
{
objCon = new ConnectionClass();
con = new OdbcConnection();
con = objCon.Connect_thru_config();
con.Open();
string str = “select *from FK_viwUser”;
//string strrole = “select name from FK_TBLROLE”;
OdbcCommand cmd = new OdbcCommand(str, con);
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView_account.DataSource = ds;
GridView_account.DataBind();
con.Close();
}//end of fillgridview

public enum ValidationCode
{
LoginFailed = 1,
LoginSucceeded = 2,
ConnectionFailed = 3,
UnspecifiedFailure = 4,
LoginCreated = 5
}//end of ValidationCode

protected void GridView_account_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedID = ((Label)GridView_account.SelectedRow.FindControl(“label_accid”)).Text;
Session[“manage”] = selectedID.ToString();
//Response.Write(“Original message :”+selectedText);
Page.Response.Redirect(“payrollfeature.aspx”);
}

protected void delete_Click(object sender, EventArgs e)
{
try
{
con.Open();
//string sql = “SELECT count(*)as rows FROM FK_TBLUSER where NAME='” + struser + “‘”;
}
catch (Exception e1)
{
Page.Response.Write(“Error in Delete : ” + e1);
}
finally { con.Close(); }
}//end of delete_click

protected void GridView_account_RowCommand(object sender, GridViewCommandEventArgs e)
{
ValidationCode result;
objCon = new ConnectionClass();
con = new OdbcConnection();
con = objCon.Connect_thru_config();

if (e.CommandName.Equals(“AddNew”))
{
TextBox name = (TextBox)GridView_account.FooterRow.FindControl(“txt_newname”);
TextBox passowrd = (TextBox)GridView_account.FooterRow.FindControl(“txt_newpassword”);
TextBox email = (TextBox)GridView_account.FooterRow.FindControl(“txt_newemail”);
passowrd.Text = “11111”;
if (name.Text == “”)
{
Page.Response.Write(“Please enter User name”);
}
else if (email.Text == “”)
{
Page.Response.Write(“Please enter Email address “);
}
else
{
int valid = checkuser(name.Text);
if (valid >= 1)
{
Page.Response.Write(“<b><font-weight: bold font-color:red >User already exists</font></b>” + valid);
}
else
{
result = CreateNewLogin(name.Text, passowrd.Text, email.Text);
if (result.Equals(“LoginCreated”))
{
Page.Response.Write(“Login has been created sucessfully :” + result);
Page.Response.Write(“<b>Welcome :<font color=\”blue\”>Login has been successfully created</font></b>”);
}
else
Page.Response.Write(“UnSuccessful: ” + result);
fillgridview();
}
}//
}
}//

protected void GridView_account_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView_account.EditIndex = e.NewEditIndex;
fillgridview();
}//

protected void GridView_account_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView_account.EditIndex = -1;
fillgridview();
}//

protected void GridView_account_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label accid = (Label)GridView_account.Rows[e.RowIndex].FindControl(“label_accid”);
TextBox name = (TextBox)GridView_account.Rows[e.RowIndex].FindControl(“txt_name”);
//TextBox passowrd = (TextBox)GridView_account.FooterRow.FindControl(“txt_password”);
objCon = new ConnectionClass();
con = new OdbcConnection();
con = objCon.Connect_thru_config();
con.Open();
string updateQuery = “update FK_TBLUSER set NAME='” + name.Text + ‘where CID='” + accid.Text
+ “‘”;
OdbcCommand updatecmd = new OdbcCommand(updateQuery, con);
updatecmd.CommandType = CommandType.Text;
updatecmd.ExecuteNonQuery();
con.Close();
GridView_account.EditIndex = -1;
fillgridview();
}//

protected void GridView_account_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string a = GridView_account.DataKeys[e.RowIndex].Values[0].ToString();
objCon = new ConnectionClass();
con = new OdbcConnection();
con = objCon.Connect_thru_config();
try
{
con.Open();
string deletequery = “delete from FK_TBLUSER where CID='” + a.ToString() + “‘”;
OdbcCommand delcmd = new OdbcCommand(deletequery, con);
delcmd.ExecuteNonQuery();
}
catch (Exception e1)
{
Page.Response.Write(“Can not delete : ” + e1);
}
finally
{
con.Close();
}
GridView_account.EditIndex = -1;
fillgridview();
}//

public ValidationCode CreateNewLogin(string strLogin, int intParent, int strType, string strPassword)
{
//Create a connection
ConnectionClass conobj = new ConnectionClass();
con = new OdbcConnection();
con = conobj.Connect_thru_config();
con.Open();
// Create a command object for the query
Page.Response.Write(“Before SQL”);
string strSQL = “INSERT INTO FK_TBLUSER (NAME,PASSWORD) ” + “VALUES(?,?)”;
Page.Response.Write(“After SQL”);
OdbcCommand objCmd = new OdbcCommand(strSQL, con);
OdbcParameter paramUsername;
paramUsername = new OdbcParameter(“@Username”, OdbcType.VarChar, 50);
paramUsername.Value = strLogin;
objCmd.Parameters.Add(paramUsername);
//for Password parameters
//Encrypt the password

MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] hashedBytes;
UTF8Encoding encoder = new UTF8Encoding();
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPassword));
OdbcParameter paramPwd;
paramPwd = new OdbcParameter(“@Password”, OdbcType.Binary, 16);
paramPwd.Value = hashedBytes;
objCmd.Parameters.Add(paramPwd);
//for User Name parameters
OdbcParameter paramUsermail;
paramUsermail = new OdbcParameter(“@Usermail”, OdbcType.VarChar, 50);
paramUsermail.Value = strEmail;
objCmd.Parameters.Add(paramUsermail);
objCmd.ExecuteNonQuery();
con.Close();
return ValidationCode.LoginCreated;
}//end of CreateNewLogin


// to check user exist or not
public int checkuser(string struser)
{
ConnectionClass conobj = new ConnectionClass();
con = new OdbcConnection();
con = conobj.Connect_thru_config();
int countuser = 0;
con.Open();
string sql = “SELECT count(*)as rows FROM FK_TBLUSER where NAME='” + struser + “‘”;
cmd = new OdbcCommand(sql, con);
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
countuser = Convert.ToInt32(myreader[“rows”]);
//Page.Response.Write(result);
}
Page.Response.Write(“Value of Result :” + countuser + “<br>”);
myreader.Close();
con.Close();
return countuser;
}

Table Structure

CREATE TABLE [FK_TBLUSER] (
[CID] [int] IDENTITY (1, 1) NOT NULL ,
[NAME] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[PASSWORD] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
CONSTRAINT [FK_TBLUSER_PK] PRIMARY KEY  CLUSTERED
(
[CID]
)  ON [PRIMARY]
) ON [PRIMARY]
GO

Please leave your comment if this post was helpful, I am also ready to hear criticism

Advertisements

20 Responses to “Dynamic GridView(Edit,Delete,Insert,Select) Just copy paste and enjoy it”

  1. Anjali said

    i wou like to know abt filters.
    how to add filters such tht on their basis data to be displayed in a datagrid

  2. praveen said

    Good Code .

  3. Ashwini said

    Hey!! Its really very very helpful.
    Very nice code.
    Thanks a lot.

  4. jas said

    it is nice article but there errors in this.

  5. Hi Jas thanks for your comments.
    could you paste your error here. we can not solve unidentified error.
    Thanks

  6. jas said

    Hi sir im sending u error list . plz go through it.

    1. missing property value in the “:”declaration.
    2. element columns is not supported
    3.element footertemplate is not supported.
    4.attributes values are without quotiton marks.
    5.Invalid token ‘>’ in class,struct,or interface member declaration.
    Thanks and regards
    Jas

  7. Hi Jas, if you are trying to copy paste the above code then you may get ‘quotation’ kind of error as in html it prints “ “ quotes instead of ” “.
    I will suggest you to write the code wherever you are getting quotes.
    and you check your GridView property whether there is column element?
    Which version of .net you are using?
    is it showing error under <asp:GridView

  8. jas said

    the link u send me is not working

  9. jas said

    can u come on gmail so that i can discuss with the issues

  10. Ray Verhaalen said

    Thank-you very much for putting this out. It has helped greatly.

  11. kabil said

    hi praveen i got this error

    “The type or namespace name ‘ConnectionClass’ could not be found (are you missing a using directive or an assembly reference?)”

  12. The ADODB namespace provides an interface named Connection. In the .NET Framework, the Connection interface is defined by a class named ConnectionClass.

    To create a connection to a database, declare a variable of type Connection or ADODB.ConnectionClass and initialize it using the new operator.
    you can do like

    using ADODB;
    ConnectionClass conDatabase = new ConnectionClass();

  13. kabil said

    ya…i solved it….thanx….do u ve any idea about filter in gridview [its like MS Excel 2007)?

  14. kvganeshbabu said

    Good.

  15. Christina said

    Congratulations! Really useful!!

  16. Please give the information about dynamic gridview in asp.net

  17. what is dynamic Gridview in asp.nt

  18. silestone colors…

    […]Dynamic GridView(Edit,Delete,Insert,Select) Just copy paste and enjoy it « Programming in almost language[…]…

  19. aarthi said

    I have a gridview being populated using datasource. In the table, I have a column ‘Staus’ which has values ,either 0 or 1. (0 for no and 1 for yes). But inthe gridview, instead of displaying 0 or 1 , I want the inferred values ‘Yes’ or ‘No’ to be displayed.

    Can this be done.

  20. @Aarthi, well you can always do that using Enum.. Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: