Friday, 28 February 2014

A Small Application to Provide Button Level Validation using C#.NET(using Single Table)

Take One DDL for Select ID,One Label for Msg, Two TextBox for ID & Desc and Six Buttons for Add,Edit,Update,Clear,Delete and Save Operation.
1.While clicking Add Button- ID of Textbox generate automatically and then write descripion on Desc Textbox and then do operation for Save,Clear Operations.
2.While selecting ID of DDL- Then do for Edit,Update,Delete,Clear Operations.

Here done Button Validation through 'Enable' features of Button and use Single Table.

Ans:-

Default.aspx:-

<%@ 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>Button Level Validation Operations</title>
    
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div class="divHeader">
    <center>
    <div class="div"><font color="white"> <marquee direction="right"><strong>TOSHFA</strong></marquee></font></div>
    <div class="divMid">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
    <table>
    <tr><td>Select/Edit</td><td>:</td><td><asp:DropDownList ID="ddlEdit" runat="server" AutoPostBack="true" onselectedindexchanged="ddlEdit_SelectedIndexChanged">
        </asp:DropDownList></td></tr>
    <tr><td>Code</td><td>:</td><td><asp:TextBox ID="txtCode" ReadOnly="true" runat="server"></asp:TextBox></td></tr>
    <tr><td>Description</td><td>:</td><td><asp:TextBox ID="txtDesc" runat="server"></asp:TextBox></td></tr>
        </table> 
        </ContentTemplate>
        </asp:UpdatePanel>                   
        </div> 
        <br />
        <asp:Label ID="lblMsg" ForeColor="Red" runat="server" Text="GetlblMsgHere"></asp:Label>
        <br />                
        <div class="divMid">                                                                                                 
        <asp:Button ID="btnAdd" CssClass="button" runat="server" Text="ADD" onclick="btnAdd_Click" 
                AccessKey="A" ToolTip="Alt+A" />
        &nbsp;
        <asp:Button ID="btnEdit" CssClass="button" runat="server" Text="Edit" onclick="btnEdit_Click" 
                AccessKey="E" ToolTip="Alt+E" />
        &nbsp;
            <asp:Button ID="btnUpdate" CssClass="button" runat="server" Text="Update" 
                onclick="btnUpdate_Click" AccessKey="U" ToolTip="Alt+U" />
         &nbsp;
            <asp:Button ID="btnClear" CssClass="button" runat="server" Text="Clear" 
                onclick="btnClear_Click" AccessKey="C" ToolTip="Alt+C" />
             &nbsp;
            <asp:Button ID="btnDelete" CssClass="button" runat="server" Text="Delete" 
                onclick="btnDelete_Click" AccessKey="D" ToolTip="Alt+D" />
             &nbsp;
            <asp:Button ID="btnSave" CssClass="button" runat="server" Text="Save" OnClientClick="validate()" onclick="btnSave_Click" 
                AccessKey="S" ToolTip="Alt+S" />
        </div>
        <div class="div">Copy Rirht-2014 @ SubsDotNet Hyderabad.</div>
   </center>
    
    </div>
    </form>
</body>
</html>

Default.aspx.cs:-

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    Class1 obj = new Class1();
    SqlConnection cn;
    SqlCommand cmd;
    SqlDataAdapter da;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            DdlVisibility();
            BtnAuthentication();
        }
    }
    void DdlVisibility()
    {
        ddlEdit.Visible = false;
    }
    void BtnAuthentication()
    {
        btnAdd.Enabled = true;
        btnEdit.Enabled = true;
        btnClear.Enabled = false;
        btnSave.Enabled = false;
        btnUpdate.Enabled = false;
        btnDelete.Enabled = false;
        txtCode.Enabled = false;
        txtDesc.Enabled = false;
    }
   void  AddBtnAuthentication()
    {
        btnAdd.Enabled = false;
        btnEdit.Enabled = false;
        txtDesc.Enabled = true;
        btnSave.Enabled = true;
        btnClear.Enabled = true;
    }
   void EditBtnAuthentication()
   {
       btnAdd.Enabled = false;
       txtDesc.Enabled = true;
       btnUpdate.Enabled = true;
       btnClear.Enabled = true;
       btnEdit.Enabled = false;
       btnDelete.Enabled = true;
   }
   void ClrbtnAuthentication()
   {
       btnClear.Enabled = false;
       btnSave.Enabled = false;
       btnUpdate.Enabled = false;
       btnDelete.Enabled = false;
       btnAdd.Enabled = true;
       btnEdit.Enabled = true;
   }
   void UpdatebtnAuthentication()
   {
       btnUpdate.Enabled = false;
       btnDelete.Enabled = false;
   }
   void SavebtnAuthentication()
   {
       btnSave.Enabled = false;
       btnClear.Enabled = true;
       
   }
   void DeletebtnAuthentication()
   {
       btnUpdate.Enabled = false;
       btnDelete.Enabled = false;
   }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        DdlVisibility();
        EditBtnAuthentication();
        ddlEdit.Visible = true;
        
        cn = new SqlConnection(obj.GetConnection());
        cn.Open();
        cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spShowData";                                //--Here get data in to the DDL from DB
        da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        ddlEdit.DataTextField = "description";
        ddlEdit.DataValueField = "code";
        ddlEdit.DataSource = dt;
        ddlEdit.DataBind();
        ddlEdit.Items.Insert(0, "--Select--");
        cn.Close();


    }
    protected void ddlEdit_SelectedIndexChanged(object sender, EventArgs e)
    {
        cn = new SqlConnection(obj.GetConnection());
        cn.Open();
        cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spEditFrmToshfa";                           //--Here change DDl value as per select
        cmd.Parameters.AddWithValue("@code", SqlDbType.Int).Value = ddlEdit.SelectedValue.ToString();
        da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            //txtName.Text=ds.Tables["Emp"].Rows[0]["name"].ToString();         // --it will use when we will take DataSet instead of DataTable

            txtCode.Text = dt.Rows[0]["code"].ToString();
            txtDesc.Text = dt.Rows[0]["description"].ToString();
        }
        cn.Close();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        AddBtnAuthentication();
        txtDesc.Focus();
        DdlVisibility();

        cn = new SqlConnection(obj.GetConnection());
        
        cmd = new SqlCommand();
        cmd.Connection = cn;

        cmd.CommandText = "select isnull(max(code),0)+1 code from toshfa";
        var j = "";
        try
        {
            cn.Open();
            j = cmd.ExecuteScalar().ToString();                        //--While using aggregate function  
            txtCode.Text = Convert.ToString(j);
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
        finally
        {
            cn.Close();
        }

        //int i = Convert.ToInt32(cmd.ExecuteScalar());                //--it is same as above 2 lines code
        //txtCode.Text =Convert.ToString(i);

        //cmd.CommandType = CommandType.StoredProcedure;          //--we can use it instead of above 3 lines code

        //cmd.CommandText = "spGetMaxCodeNo";
        //da = new SqlDataAdapter(cmd);
        //DataTable dt = new DataTable();
        //da.Fill(dt);
        //if (dt.Rows.Count >= 0)
        //{
        //    txtCode.Text = dt.Rows[0]["code"].ToString();
        //}

    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        ClrbtnAuthentication();
        DdlVisibility();

        txtCode.Text = string.Empty.ToString();
        txtDesc.Text = string.Empty.ToString();
        ddlEdit.Items.Clear();
        lblMsg.Text = "All Cleared..Go Ahead...";
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        SavebtnAuthentication();

        cn = new SqlConnection(obj.GetConnection());
        cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spSaveToshfaData";

        cmd.Parameters.Add("@code", txtCode.Text);            //--depricated/expired-we can use below code
        cmd.Parameters.Add("@description", txtDesc.Text);
        cmd.Parameters.Add("@smode", "0");
        int i = 0;
        try
        {
            cn.Open();
            i = cmd.ExecuteNonQuery();
            if (i > 0)
            {
                lblMsg.Text = "Added Successfully..";
            }
            else
            {
                lblMsg.Text = "Not Added Successfully..";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
        finally
        {
            cn.Close();
        }
       

        //cmd.Parameters.AddWithValue("@code", SqlDbType.Int).Value = txtCode.Text;            //--we can use it instead of above depricated/expired lines code

        //cmd.Parameters.AddWithValue("@description", SqlDbType.VarChar).Value = txtDesc.Text;

        //da = new SqlDataAdapter(cmd);                               //--No need of use it for update single record
        //DataTable dt = new DataTable();
        //da.Fill(dt);

        //int rowAffected = cmd.ExecuteNonQuery();
        //if (rowAffected > 0)
        //{
        //    lblMsg.Text = "Added Successfully..";
        //}
        //else
        //{
        //    lblMsg.Text = "Not Added Successfully..";
        //}


        //txtCode.Text = string.Empty.ToString();               //--we can use it for clearing txtbx bt no need here
        //txtDesc.Text = string.Empty.ToString();
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        DeletebtnAuthentication();

        cn = new SqlConnection(obj.GetConnection());
       
        cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spDeleteFromToshfa";
        cmd.Parameters.AddWithValue("@code", txtCode.Text);

        //da = new SqlDataAdapter(cmd);                           //--No need of use it for update single record
        //DataTable dt = new DataTable();
        //da.Fill(dt);

        int rowAffected = 0;
        try
        {
            cn.Open();
            rowAffected = cmd.ExecuteNonQuery();
            if (rowAffected > 0)
            {
                lblMsg.Text = "Deleteded Successfully..";
            }
            else
            {
                lblMsg.Text = "Not Deleted Successfully..";
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
        finally
        {
            cn.Close();
        }
        //txtCode.Text = string.Empty.ToString();              //--we can use it for clearing txtbx bt no need here
        //txtDesc.Text = string.Empty.ToString();
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        DdlVisibility();
        UpdatebtnAuthentication();

        cn = new SqlConnection(obj.GetConnection());
        
        cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spUpdateToshfaData";
        cmd.Parameters.AddWithValue("@code", SqlDbType.Int).Value = txtCode.Text;
        cmd.Parameters.AddWithValue("@description", SqlDbType.VarChar).Value = txtDesc.Text;

        //da = new SqlDataAdapter(cmd);                                  //--No need of use it for update single record
        //DataTable dt = new DataTable();
        //da.Fill(dt);

        int rowAffected = 0;
        try
        {
            cn.Open();
            rowAffected = cmd.ExecuteNonQuery();
            if (rowAffected > 0)
            {
                lblMsg.Text = "Updated Successfully..";
            }
            else
            {
                lblMsg.Text = "Not Updated Successfully..";
            }
        }
            catch(Exception ex)
        {
                lblMsg.Text =ex.Message;
        }
        finally
        {
            cn.Close();
        }

        //txtCode.Text = string.Empty.ToString();                                      // --we can use it for clearing txtbx bt no need here
        //txtDesc.Text = string.Empty.ToString();
    }
}

Get Connection Through Class File:-

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
public Class1()
{
//
// TODO: Add constructor logic here
//
}
    public string GetConnection()
    {
        string strCon = "server=192.168.0.200;database=subsdb;user id=sa;pwd=amtpl@123";
        return strCon;
    }
    
}

For Style write code in CSS file:-

.divHeader
{
    border-color:Red;
    border-style:solid;
    border-width:2px;
    
    }
.div
{
    background-color:Gray;
}
.divMid
{
background-color:#CCFFFF;
}
.button{ background-color:Aqua; 
         border-bottom-color:Black; 
         width:70px; 
         height:25px
}

For Create Table & Stored Procedure:-

use subsdb

create table toshfa(code int constraint p_key primary key,description varchar(30))

--Insert code by max() & pass variable of description
--create proc spAddInToshfa(@description varchar(30))
--as
--begin
--insert into toshfa(code,description)values((select isnull(MAX(code),0)+1 from toshfa),@description)
--end

--exec spAddInToshfa 'fdsgggg'

--insert into test(id,name)values((select isnull(MAX(id),0)+1 from test),'nname')

--Delete

create proc spDeleteFromToshfa(@code int)
as
begin
delete from toshfa where code=@code;
end

exec spDeleteFromToshfa 2

--Edit/using selecting DDL and show in txtbx

alter proc spEditFrmToshfa(@code int)
as
begin
select code,description from toshfa where code=@code;
end

--Show Data

create proc spShowData
as
begin
select description+'-'+cast(code as varchar)as description,code  from toshfa
end

--Get Max Code

create proc spGetMaxCodeNo
as
begin
select MAX(code)+1 as code from toshfa;
end

--Save

CREATE proc spSaveToshfaData(@code int,@description varchar(30),@smode int)
as
begin
if @smode=0
begin
select @code=isnull(max(code),0)+1 from toshfa
insert into toshfa(code,description)values(@code,@description)
end
else
begin
update toshfa set description=@description  where code=@code
end
end

--Save
--create proc spSaveToshfaData(@code int,@description varchar(30))
--as
--begin
--insert into toshfa(code,description)values(@code,@description)
--end

--Update

create proc spUpdateToshfaData(@code int,@description varchar(30))
as
begin
update toshfa set description=@description where code=@code;
end

exec spUpdateToshfaData 1,'subs'

No comments:

Post a Comment